mirror of
https://github.com/LCTT/TranslateProject.git
synced 2024-12-26 21:30:55 +08:00
Merge branch 'master' of https://github.com/LCTT/TranslateProject into translating
This commit is contained in:
commit
1be43c5919
@ -2,7 +2,7 @@
|
||||
[#]: via: "https://opensource.com/article/22/5/linux-advice-beginners"
|
||||
[#]: author: "Opensource.com https://opensource.com/users/admin"
|
||||
[#]: collector: "lkxed"
|
||||
[#]: translator: " "
|
||||
[#]: translator: "lightchaserhy"
|
||||
[#]: reviewer: " "
|
||||
[#]: publisher: " "
|
||||
[#]: url: " "
|
||||
|
@ -1,204 +0,0 @@
|
||||
[#]: subject: (Write your first JavaScript code)
|
||||
[#]: via: (https://opensource.com/article/21/7/javascript-cheat-sheet)
|
||||
[#]: author: (Seth Kenlon https://opensource.com/users/seth)
|
||||
[#]: collector: (lujun9972)
|
||||
[#]: translator: ( )
|
||||
[#]: reviewer: ( )
|
||||
[#]: publisher: ( )
|
||||
[#]: url: ( )
|
||||
|
||||
Write your first JavaScript code
|
||||
======
|
||||
JavaScript was created for the web, but it can do so much more. Learn
|
||||
the basics, then download our cheat sheet so you always have the details
|
||||
at hand.
|
||||
![Code with javascript on white background][1]
|
||||
|
||||
JavaScript is a programming language full of pleasant surprises. Many people first encounter JavaScript as a language for the web. There's a JavaScript engine in all the major browsers, there are popular frameworks such as JQuery, Cash, and Bootstrap to help make web design easier, and there are even programming environments written in JavaScript. It seems to be everywhere on the internet, but it turns out that it's also a useful language for projects like [Electron][2], an open source toolkit for building cross-platform desktop apps with JavaScript.
|
||||
|
||||
JavaScript is a surprisingly multipurpose language with a wide assortment of libraries for much more than just making websites. Learning the basics of the language is easy, and it's a gateway to building whatever you imagine.
|
||||
|
||||
### Install JavaScript
|
||||
|
||||
As you progress with JavaScript, you may find yourself wanting advanced JavaScript libraries and runtimes. When you're just starting, though, you don't have to install JavaScript at all. All major web browsers include a JavaScript engine to run the code. You can write JavaScript using your favorite text editor, load it into your web browser, and see what your code does.
|
||||
|
||||
### Get started with JavaScript
|
||||
|
||||
To write your first JavaScript code, open your favorite text editor, such as [Notepad++][3], [Atom][4], or [VSCode][5]. Because it was developed for the web, JavaScript works well with HTML, so first, just try some basic HTML:
|
||||
|
||||
|
||||
```
|
||||
<[html][6]>
|
||||
<[head][7]>
|
||||
<[title][8]>JS</[title][8]>
|
||||
</[head][7]>
|
||||
<[body][9]>
|
||||
<[p][10] id="example">Nothing here.</[p][10]>
|
||||
</[body][9]>
|
||||
</[html][6]>
|
||||
```
|
||||
|
||||
Save the file, and then open it in a web browser.
|
||||
|
||||
![HTML displayed in browser][11]
|
||||
|
||||
(Seth Kenlon, [CC BY-SA 4.0][12])
|
||||
|
||||
To add JavaScript to this simple HTML page, you can either create a JavaScript file and refer to it in the page's `head` or just embed your JavaScript code in the HTML using the `<script>` tag. In this example, I embed the code:
|
||||
|
||||
|
||||
```
|
||||
<[html][6]>
|
||||
<[head][7]>
|
||||
<[title][8]>JS</[title][8]>
|
||||
</[head][7]>
|
||||
<[body][9]>
|
||||
<[p][10] id="example">Nothing here.</[p][10]>
|
||||
|
||||
<[script][13]>
|
||||
let myvariable = "Hello world!";
|
||||
|
||||
document.getElementById("example").innerHTML = myvariable;
|
||||
</[script][13]>
|
||||
|
||||
</[body][9]>
|
||||
</[html][6]>
|
||||
```
|
||||
|
||||
Reload the page in your browser.
|
||||
|
||||
![HTML with JavaScript displayed in browser][14]
|
||||
|
||||
(Seth Kenlon, [CC BY-SA 4.0][12])
|
||||
|
||||
As you can see, the `<p>` tag as written still contains the string "Nothing here," but when it's rendered, JavaScript alters it so that it contains "Hello world" instead. Yes, JavaScript has the power to rebuild (or just help build) a webpage.
|
||||
|
||||
The JavaScript in this simple script does two things. First, it creates a variable called `myvariable` and places the string "Hello world!" into it. Finally, it searches the current document (the web page as the browser is rendering it) for any HTML element with the ID `example`. When it locates `example`, it uses the `innerHTML` function to replace the contents of the HTML element with the contents of `myvariable`.
|
||||
|
||||
Of course, using a custom variable isn't necessary. It's just as easy to populate the HTML element with something being dynamically created. For instance, you could populate it with a timestamp:
|
||||
|
||||
|
||||
```
|
||||
<[html][6]>
|
||||
<[head][7]>
|
||||
<[title][8]>JS</[title][8]>
|
||||
</[head][7]>
|
||||
<[body][9]>
|
||||
<[p][10] id="example">Date and time appears here.</[p][10]>
|
||||
|
||||
<[script][13]>
|
||||
document.getElementById("example").innerHTML = Date();
|
||||
</[script][13]>
|
||||
|
||||
</[body][9]>
|
||||
</[html][6]>
|
||||
```
|
||||
|
||||
Reload the page to see a timestamp generated at the moment the page is rendered. Reload a few times to watch the seconds increment.
|
||||
|
||||
### JavaScript syntax
|
||||
|
||||
In programming, **syntax** refers to the rules of how sentences (or "lines") are written. In JavaScript, each line of code must end in a semicolon (`;`) so that the JavaScript engine running your code understands when to stop reading.
|
||||
|
||||
Words (or "strings") must be enclosed in quotation marks (`"`), while numbers (or "integers") go without.
|
||||
|
||||
Almost everything else is a convention of the JavaScript language, such as variables, arrays, conditional statements, objects, functions, and so on.
|
||||
|
||||
### Creating variables in JavaScript
|
||||
|
||||
Variables are containers for data. You can think of a variable as a box where you can put data to share with your program. Creating a variable in JavaScript is done with two keywords you choose based on how you intend to use the variable: `let` and `var`. The `var` keyword denotes a variable intended for your entire program to use, while `let` creates variables for specific purposes, usually inside functions or loops.
|
||||
|
||||
JavaScript's built-in `typeof` function can help you identify what kind of data a variable contains. Using the first example, you can find out what kind of data `myvariable` contains by modifying the displayed text to:
|
||||
|
||||
|
||||
```
|
||||
<string>
|
||||
let myvariable = "Hello world!";
|
||||
document.getElementById("example").innerHTML = typeof(myvariable);
|
||||
</string>
|
||||
```
|
||||
|
||||
This renders "string" in your web browser because the variable contains "Hello world!" Storing different kinds of data (such as an integer) in `myvariable` would cause a different data type to be printed to your sample web page. Try changing the contents of `myvariable` to your favorite number and then reloading the page.
|
||||
|
||||
### Creating functions in JavaScript
|
||||
|
||||
Functions in programming are self-contained data processors. They're what makes programming _modular_. It's because functions exist that programmers can write generic libraries that, for instance, resize images or keep track of the passage of time for other programmers (like you) to use in their own code.
|
||||
|
||||
You create a function by providing a custom name for your function followed by any amount of code enclosed within braces.
|
||||
|
||||
Here's a simple web page featuring a resized image and a button that analyzes the image and returns the true image dimensions. In this example code, the `<button>` HTML element uses the built-in JavaScript function `onclick` to detect user interaction, which triggers a custom function called `get_size`:
|
||||
|
||||
|
||||
```
|
||||
<[html][6]>
|
||||
<[head][7]>
|
||||
<[title][8]>Imager</[title][8]>
|
||||
</[head][7]>
|
||||
<[body][9]>
|
||||
|
||||
<[div][15]>
|
||||
<[button][16] onclick="get_size(document.getElementById('myimg'))">
|
||||
Get image size
|
||||
</[button][16]>
|
||||
</[div][15]>
|
||||
|
||||
<[div][15]>
|
||||
<[img][17] style="width: 15%" id="myimg" src="penguin.png" />
|
||||
</[div][15]>
|
||||
|
||||
<[script][13]>
|
||||
function get_size(i) {
|
||||
let w = i.naturalWidth;
|
||||
let h = i.naturalHeight;
|
||||
alert(w + " by " + h);
|
||||
}
|
||||
</[script][13]>
|
||||
|
||||
</[body][9]>
|
||||
</[html][6]>
|
||||
```
|
||||
|
||||
Save the file and load it into your web browser to try the code.
|
||||
|
||||
![Custom get_size function returns image dimensions][18]
|
||||
|
||||
(Seth Kenlon, [CC BY-SA 4.0][12])
|
||||
|
||||
### Cross-platform apps with JavaScript
|
||||
|
||||
You can see from the code sample how JavaScript and HTML work closely together to create a cohesive user experience. This is one of the great strengths of JavaScript. When you write code in JavaScript, you inherit one of the most common user interfaces of modern computing regardless of platform: the web browser. Your code is cross-platform by nature, so your application, whether it's just a humble image size analyzer or a complex image editor, video game, or whatever else you dream up, can be used by everyone with a web browser (or a desktop, if you deliver an Electron app).
|
||||
|
||||
Learning JavaScript is easy and fun. There are lots of websites with tutorials available. There are also over a million JavaScript libraries to help you interface with devices, peripherals, the Internet of Things, servers, file systems, and lots more. And as you're learning, keep our [**JavaScript cheat sheet**][19] close by so you remember the fine details of syntax and structure.
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
via: https://opensource.com/article/21/7/javascript-cheat-sheet
|
||||
|
||||
作者:[Seth Kenlon][a]
|
||||
选题:[lujun9972][b]
|
||||
译者:[lixin555](https://github.com/lixin555)
|
||||
校对:[校对者ID](https://github.com/校对者ID)
|
||||
|
||||
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
|
||||
|
||||
[a]: https://opensource.com/users/seth
|
||||
[b]: https://github.com/lujun9972
|
||||
[1]: https://opensource.com/sites/default/files/styles/image-full-size/public/lead-images/code2.png?itok=JCJTJszs (Code with javascript on white background)
|
||||
[2]: https://www.electronjs.org/
|
||||
[3]: https://opensource.com/article/16/12/notepad-text-editor
|
||||
[4]: https://opensource.com/article/20/12/atom
|
||||
[5]: https://opensource.com/article/20/6/open-source-alternatives-vs-code
|
||||
[6]: http://december.com/html/4/element/html.html
|
||||
[7]: http://december.com/html/4/element/head.html
|
||||
[8]: http://december.com/html/4/element/title.html
|
||||
[9]: http://december.com/html/4/element/body.html
|
||||
[10]: http://december.com/html/4/element/p.html
|
||||
[11]: https://opensource.com/sites/default/files/pictures/plain-html.jpg (HTML displayed in browser)
|
||||
[12]: https://creativecommons.org/licenses/by-sa/4.0/
|
||||
[13]: http://december.com/html/4/element/script.html
|
||||
[14]: https://opensource.com/sites/default/files/uploads/html-javascript.jpg (HTML with JavaScript displayed in browser)
|
||||
[15]: http://december.com/html/4/element/div.html
|
||||
[16]: http://december.com/html/4/element/button.html
|
||||
[17]: http://december.com/html/4/element/img.html
|
||||
[18]: https://opensource.com/sites/default/files/uploads/get-size.jpg (Custom get_size function returns image dimensions)
|
||||
[19]: https://opensource.com/downloads/javascript-cheat-sheet
|
@ -0,0 +1,159 @@
|
||||
[#]: subject: "A Quick Look at Cloud Cost Management Tools"
|
||||
[#]: via: "https://www.opensourceforu.com/2022/06/a-quick-look-at-cloud-cost-management-tools/"
|
||||
[#]: author: "Dr Anand Nayyar https://www.opensourceforu.com/author/anand-nayyar/"
|
||||
[#]: collector: "lkxed"
|
||||
[#]: translator: " "
|
||||
[#]: reviewer: " "
|
||||
[#]: publisher: " "
|
||||
[#]: url: " "
|
||||
|
||||
A Quick Look at Cloud Cost Management Tools
|
||||
======
|
||||
Whether you are using a single cloud computing service provider or operating in a multi-cloud or hybrid cloud computing environment, you may be paying for resources that your organisation does not use at all. That is why cloud cost management is so important.
|
||||
|
||||
![Cloud cost management tools][1]
|
||||
|
||||
If you are a developer or software engineer, you will be using a range of cloud resources. Managing cloud costs, and knowing exactly where and why the expenditure on the cloud is happening is a huge challenge. If cloud-native technologies like microservices, containers and Kubernetes are being used, cloud utilisation may not be fully visible and the organisation may end up paying for far more services than have been used.
|
||||
|
||||
![Figure 1: Cost per customer report][2]
|
||||
|
||||
### What is cloud cost management?
|
||||
|
||||
Cloud cost management is defined as the efficient monitoring, measuring and control of cloud costs. Traditionally, cloud cost management focused on cutting down cloud cost wastages in terms of under-utilised and forgotten resources but, nowadays, it focuses on architectural optimisation.
|
||||
|
||||
The advantages of cloud cost management are:
|
||||
|
||||
* High accuracy in the planning, budgeting and forecasting of cloud services
|
||||
* Re-architecting resources for more profit
|
||||
* Reducing operational costs and decommissioning wasteful services
|
||||
* Effective load balancing management and better usage of computing resources
|
||||
|
||||
Cloud native cost management services
|
||||
|
||||
AWS Cloud Economics Center
|
||||
Though the key driver for any enterprise to migrate to a cloud platform is better total cost of ownership (TCO), the benefits don’t stop there today. Cloud economics or FinOps is the term used for creating a framework that can help to derive the expenditure in cloud adoption.
|
||||
|
||||
![Figure 2: Amazon cost management solutions][3]
|
||||
|
||||
When a business is growing, good planning, budget control and predicting the pattern of cloud asset usage are important. Cloud economics addresses this space. There are many third party tools like CloudHealth, Densify or Apptio Cloudability available as cost management tools, which come with financial management, advisory and advanced analytics. Most of these tools work on any cloud platform — Azure, AWS or GCP.
|
||||
|
||||
At the same time, there are native tools available as well for cost management like the AWS Economics Center or Cost Management console.
|
||||
|
||||
AWS Economics is based on a cloud value framework and has the following benefits.
|
||||
|
||||
* Cost savings: Offers usage details on the cloud assets and TCO calculation to compare with existing and forecasted spends.
|
||||
* Staff productivity: Improved automation tasks like DevOps pipeline, automated code review, and automated cost optimisation alerts reduce manual efforts.
|
||||
* Operational resilience: A well-architected framework is used to ensure high availability, security and compliance, leading to highly resilient cloud platform usage.
|
||||
* Business agility: Reduces errors in cloud deployment by using best practices and AWS partner solutions.
|
||||
|
||||
![Figure 3: AWS cost management dashboard][4]
|
||||
|
||||
### Azure cloud cost management
|
||||
|
||||
A well-architected framework has five pillars of cloud architecture development — cost optimisation, performance efficiency, operational excellence, reliability and security. Of these, cost optimisation will give immediate to long-term benefits, and requires a cost adoption framework and operating model to build an efficient cost pillar.
|
||||
|
||||
Cloud cost management includes cost transparency and cost governance as per the FinOps framework guidance. This can be implemented by using the Crawl-Walk-Run principle, where we start with cost transparency and the operating model (crawl), move towards cost optimisation and automation (walk) and, finally, implement cost management solutions and governance policies for efficient cost optimisation (run).
|
||||
|
||||
The Azure platform calls this the Build-Measure-Learn principle (similar to the Crawl-Walk-Run principle). It suggests reviewing the cost principles, including right-sizing of resources and resource tagging, and then developing a cost model to decide the billing models for resources. These will capture cost requirements, policies for infrastructure provisioning and associated budget allocation. Cost alerts and budget thresholds should also be set.
|
||||
|
||||
Resources should be tagged so that priorities can be set in cost allocation for production and non-production environments, to create a workflow process in budget management.
|
||||
|
||||
![Figure 4: AWS Trusted Advisor][5]
|
||||
|
||||
### Google cost visibility services
|
||||
|
||||
The Google Cloud Platform or GCP cost management suite is built on three tools.
|
||||
|
||||
* Cost visibility: Provides the cost per resource.
|
||||
|
||||
* Resource usage optimisation: The cost advisory facility helps you to tune the cost per resource by giving the history of and the prediction for cloud service usage.
|
||||
|
||||
* Pricing efficiency: Advisory guidelines are given to optimise the cloud services, like use of cost-efficient compute or storage resources based on usage patterns.
|
||||
|
||||
![Figure 5: Azure guidance principles for cost optimisation (Image source: Azure documentation)][6]
|
||||
|
||||
Cost management tools provide dashboard visualisation of resource usage. Alerts are given with respect to over usage or under usage of services, and a usage summary can be scheduled (weekly, monthly or quarterly). Billing exports to CSV or JSON files can be used for historical analysis.
|
||||
|
||||
Google Cloud Platform (GCP) also has many native cloud services for cloud billing; it has reporting, forecasting and optimisation features for compute and storage services, some of which are listed below.
|
||||
|
||||
* Cost management provides visualisation reports on service utilisation, filtered by labels. Data Studio can be used to build custom dashboards.
|
||||
* Billing APIs and data collection APIs (StackDriver, Resource Manager API) offer integration with native and third party cost management tools.
|
||||
* Google Recommender can be used for optimising cost and usage, based on patterns of resource usage. Resource hierarchy can be used for fine grained resource management for cost allocation.
|
||||
* Quota limits can be used to proactively control the spend rate on resources including apps and infrastructure.
|
||||
* Budgets and alerts can throttle cap costs to control spends. These can be used to closely monitor costs, and send alerts through an SMS or e-mail using programmatic budget notifications.
|
||||
* GCP can be integrated with ‘Cloud Build’, ‘Cloud Pub/Sub’ (event/alerts) and cloud functions for cost reporting, billing and notifications.
|
||||
|
||||
![Figure 6: GCP cost summary dashboard (Image source: Google documentation)][7]
|
||||
|
||||
### Some best practices to handle cloud costs efficiently
|
||||
|
||||
Cost management and cost transparency are the two common principles of cloud governance. The FinOps framework addresses both these principles.
|
||||
|
||||
The top seven ways to optimise cloud cost usage are listed below.
|
||||
|
||||
* Shutdown unused resources/instances: A common issue in resource optimisation is handling unused resources or instances, particularly in non-production environments. Monitoring and controlling these will enable better cost optimisation.
|
||||
* Right-size underused resources: During cloud migration, infrastructure sizing is done based on the existing on-premises infrastructure. We may not know the performance requirements (completely) at the initial stage, and hence right-sizing resources like VM instances, storage services and database size can help reduce costs.
|
||||
* Reserve instances or spot instances for consistent long-term workloads: When moving to the cloud, we generally have a clear idea of what we need for long-term usage like data lakes or FTP landing zone. For these services, using reserved or spot instances for three to five years can give as much as 50 per cent cost benefit.
|
||||
* Choose the hybrid cloud approach for reducing migration costs: Instead of moving all applications at once to the cloud, we can migrate in stages, keeping some key applications on-premises.
|
||||
* Use auto-scaling features for the required resources: Many cloud services have the auto-scale feature, which helps to scale-up computing and storage when there is higher usage and scale these down in case of lower usage. This feature too helps to reduce costs.
|
||||
Budget your resources: We can set a quota for resources using a budget and cost allocation, so that if there is dynamic burst in resource requirement it can be controlled well within the allocated budget by enabling alerts and notifications.
|
||||
* Choose the right compute services for better performance and costs: Though cloud service providers like Azure, AWS and GCP have multiple compute models and instance types, we may not know if we are using the right compute size and model. If we can optimise the compute model considering performance and technical requirements, we can manage costs better.
|
||||
|
||||
### Open source cloud cost management tools
|
||||
|
||||
#### Kube-Downscaler
|
||||
|
||||
Kube-Downscaler is an open source framework written in Python, which can be used to handle automatic shutdowns or set the uptime for Kubernetes worker pods based on usage patterns (for example, shutdown during the weekend and set uptime during office hours).
|
||||
|
||||
This framework runs on a single pod in the Kubernetes cluster and can work with Azure (AKS), AWS (EKS) and GCP (GKE). It has a configuration setup that can be given for the shutdown time period or uptime running period. It can be scheduled to run once or regularly for a given period (monthly, yearly).
|
||||
|
||||
![Figure 7: Integrated FinOps toolchain ecosystem][8]
|
||||
|
||||
Alternatively, we can use Kubernetes-Ops, which is another open source framework for handling end-to-end Kubernetes clusters. It can create pods/clusters, and manage, deploy, scale and monitor them in a single pane of glass.
|
||||
|
||||
#### Kubecost
|
||||
|
||||
Though cloud cost governance aims at managing compute and storage services to a large extent, managing container costs is also a challenging exercise.
|
||||
|
||||
Kubecost helps to get monthly spends, costs for name space level, and deployment resource costs; it identifies cost efficiency in a Kubernetes clustered environment. It comes in both a free-to-use open source model (where there are limitations to using it such as a single cluster, metric retention period) and a commercial model.
|
||||
|
||||
We can get details of underutilised or over-provisioned resources (nodes and pods, and abandoned resources) based on usage footprints. The major features of Kubecost are cost allocation across nodes and pods, unified cost monitoring with integrated dashboard, cost optimisation insights to identify under-provisioned or over-provisioned cluster resources, and cost alerts as well as notifications for anomalous behaviour in resource usage.
|
||||
|
||||
Kubecost can be used with Azure Kubernetes Service (AKS), Amazon’s Elastic Kubernetes Service (EKS) and Fargate, Google Kubernetes Engine (GKE) and other Kubernetes platforms in private cloud environments.
|
||||
|
||||
### Integrated FinOps toolchain solution
|
||||
|
||||
FinOps is more of a culture adoption and is driven by the three-dimensional approach for cloud cost management — people (cost administration, team structure, training), processes (cost levers, maturity models, metrics definitions) and tools (cost management services, third party tools, cost advisory services).
|
||||
|
||||
FinOps is a collaborative activity between the finance/procurement team, technical IT operations team, and business management (COO, CIO). It can be developed as an agnostic framework for implementation in a multi-cloud environment (public/private/hybrid). It can also be easily integrated with third party tools for flexible implementation. For example, developing reports and dashboards could be made flexible with this integration of third-party tools.
|
||||
|
||||
![Figure 8: Kubecost dashboard (Image source: Azure documentation)][9]
|
||||
|
||||
### Future trends in FinOps adoption
|
||||
|
||||
The adoption of FinOps is maturing in most organisations that have substantial cloud consumption as they need processes and procedures to manage, monitor, allocate and forecast cloud spending. With the introduction of FinOps, organisations will have deeper insights into the resources available or reserved, which will promote appropriate procurement of cloud resources and avoid unnecessary spend in the first place.
|
||||
|
||||
Choosing between the right FinOps platform from cloud services providers (Azure Cost Management, AWS Cost Explorer and GCP Cost Tools), third party options or in-house development is not an easy task. Factors like variability in size and usage of cloud resources, fast-changing technology, and the advent of new cloud use cases complicate the process of automating cost optimisation. Building a governance culture and mindset is vital, but not always easy.
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
via: https://www.opensourceforu.com/2022/06/a-quick-look-at-cloud-cost-management-tools/
|
||||
|
||||
作者:[Dr Anand Nayyar][a]
|
||||
选题:[lkxed][b]
|
||||
译者:[译者ID](https://github.com/译者ID)
|
||||
校对:[校对者ID](https://github.com/校对者ID)
|
||||
|
||||
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
|
||||
|
||||
[a]: https://www.opensourceforu.com/author/anand-nayyar/
|
||||
[b]: https://github.com/lkxed
|
||||
[1]: https://www.opensourceforu.com/wp-content/uploads/2022/04/Cloud-cost-management-tools.jpg
|
||||
[2]: https://www.opensourceforu.com/wp-content/uploads/2022/04/Fig1-CloudZero.jpg
|
||||
[3]: https://www.opensourceforu.com/wp-content/uploads/2022/04/Figure-2.jpg
|
||||
[4]: https://www.opensourceforu.com/wp-content/uploads/2022/04/Figuer-3.jpg
|
||||
[5]: https://www.opensourceforu.com/wp-content/uploads/2022/04/Figure-4.jpg
|
||||
[6]: https://www.opensourceforu.com/wp-content/uploads/2022/04/Figure-5.jpg
|
||||
[7]: https://www.opensourceforu.com/wp-content/uploads/2022/04/Figure-6.jpg
|
||||
[8]: https://www.opensourceforu.com/wp-content/uploads/2022/04/Figure-7.jpg
|
||||
[9]: https://www.opensourceforu.com/wp-content/uploads/2022/04/Figure-8.jpg
|
@ -0,0 +1,127 @@
|
||||
[#]: subject: "Thonny is an Ideal IDE for Teaching Python Programming in Schools"
|
||||
[#]: via: "https://itsfoss.com/thonny-python-ide/"
|
||||
[#]: author: "Abhishek Prakash https://itsfoss.com/author/abhishek/"
|
||||
[#]: collector: "lkxed"
|
||||
[#]: translator: " "
|
||||
[#]: reviewer: " "
|
||||
[#]: publisher: " "
|
||||
[#]: url: " "
|
||||
|
||||
Thonny is an Ideal IDE for Teaching Python Programming in Schools
|
||||
======
|
||||
Running a Python program in Linux is as simple as executing the Python file in the terminal.
|
||||
|
||||
But that’s not very convenient for everyone and it doesn’t help you debug your programs. Too raw.
|
||||
|
||||
There are several IDEs and text editors that can be used for Python development. The [PyCharm community edition is available for Linux users][1].
|
||||
|
||||
I recently came across another IDE specifically crafted for Python beginners. I liked the idea of this application and hence I am sharing it with you here.
|
||||
|
||||
### Thonny is a cross-platform, open source Python IDE for beginners
|
||||
|
||||
[Thonny][2] feels like the Python version of Eclipse in terms of UI and UX. And that’s not entirely a bad thing considering most C++ and Java beginners start with Eclipse and many stay with it afterward.
|
||||
|
||||
It’s not a new tool. It has been on the horizon for some years now. I don’t code in Python so I never discovered it until recently.
|
||||
|
||||
Dedicated to Python, Thonny has features that help Python beginners understand how their program behaves. Let’s take a look at those features.
|
||||
|
||||
#### Plug and play
|
||||
|
||||
Thonny comes with Python so you don’t need to do additional effort for installing Python. That’s not a big deal for Linux users as most distributions have Python installed by default.
|
||||
|
||||
The interface is simple. It gives you an editor where you can write your Python program and hit the Run button or use F5 key to play the program. The output is displayed at the bottom.
|
||||
|
||||
![thonny hello world][3]
|
||||
|
||||
#### See variables
|
||||
|
||||
From the View->Variables, you can see the values of all the variables. No need to print them all.
|
||||
|
||||
![thonny variable pane][4]
|
||||
|
||||
#### Built-in debugger
|
||||
|
||||
Run your program step by step by using the debugger. You can access it from the top menu or use the Ctrl+F5 keys. You don’t even need the breakpoints here. You can go into big steps with F6 or in small steps with F7.
|
||||
|
||||
![thonny step by step f6][5]
|
||||
|
||||
In small steps, you can see how Python sees your expressions. This is very helpful for new programmers to understand why their program is behaving in a certain manner.
|
||||
|
||||
![thonny step by step f7][6]
|
||||
|
||||
That’s not it. For function calls, it opens a new window with separate local variables table and code pointer. Super cool!
|
||||
|
||||
#### Syntax error highlighter
|
||||
|
||||
Beginners often make simple syntax errors like missing paranthesis, quotes etc. Thonny is points it out immediately in the editor itself.
|
||||
|
||||
Local variables are also visually distinguished from globals.
|
||||
|
||||
#### Auto completion
|
||||
|
||||
You don’t have to type everything. Thonny supports auto code completion which helps in coding faster.
|
||||
|
||||
![thonny auto complete][7]
|
||||
|
||||
#### Access to system shell
|
||||
|
||||
From the Tools, you can access the system shell. From here you can install new Python package or learn to handle Python from the command line.
|
||||
|
||||
![thonny shell terminal][8]
|
||||
|
||||
Please note that if you use Flatpak or Snap, Thonny may not be able to access the system shell.
|
||||
|
||||
#### Manage Pip from GUI
|
||||
|
||||
Go to Tools and Manage packages. It opens a window and you can install Pip packages from this GUI.
|
||||
|
||||
![thonny manage packages][9]
|
||||
|
||||
Good enough features for learning Python, right? Let’s see how to install it.
|
||||
|
||||
### Installing Thonny on Linux
|
||||
|
||||
Thonny is a cross-platform application. It is available for Windows, macOS and Linux.
|
||||
|
||||
It’s a popular application and you can find it in the repositories of most Linux distributions. Just look for it in your system’s software center.
|
||||
|
||||
Alternatively, you can always use the package manager of your Linux distribution.
|
||||
|
||||
On Debian and Ubuntu-based distributions, you can use the apt command to install it.
|
||||
|
||||
```
|
||||
sudo apt install thonny
|
||||
```
|
||||
|
||||
It downloads a bunch of dependencies and around 300 MB of packages.
|
||||
|
||||
Once installed, you can search for it in the menu and install it from there.
|
||||
|
||||
### Conclusion
|
||||
|
||||
Thonny is a decent tool for beginner Python programmers. Not that experts cannot use it but it’s more suited to be used in the schools and colleges. Students will find it helpful in learning Python and understanding how their code behaves in certain manner. In fact, it was originally developed in University of Tartu, Estonia.
|
||||
|
||||
Overall, a good software for Python learners.
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
via: https://itsfoss.com/thonny-python-ide/
|
||||
|
||||
作者:[Abhishek Prakash][a]
|
||||
选题:[lkxed][b]
|
||||
译者:[译者ID](https://github.com/译者ID)
|
||||
校对:[校对者ID](https://github.com/校对者ID)
|
||||
|
||||
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
|
||||
|
||||
[a]: https://itsfoss.com/author/abhishek/
|
||||
[b]: https://github.com/lkxed
|
||||
[1]: https://itsfoss.com/install-pycharm-ubuntu/
|
||||
[2]: https://thonny.org/
|
||||
[3]: https://itsfoss.com/wp-content/uploads/2022/06/thonny-hello-world.png
|
||||
[4]: https://itsfoss.com/wp-content/uploads/2022/06/thonny-variable-pane.png
|
||||
[5]: https://itsfoss.com/wp-content/uploads/2022/06/thonny-step-by-step-f6.png
|
||||
[6]: https://itsfoss.com/wp-content/uploads/2022/06/thonny-step-by-step-f7.png
|
||||
[7]: https://itsfoss.com/wp-content/uploads/2022/06/thonny-auto-complete.png
|
||||
[8]: https://itsfoss.com/wp-content/uploads/2022/06/thonny-shell-terminal.png
|
||||
[9]: https://itsfoss.com/wp-content/uploads/2022/06/thonny-manage-packages.png
|
221
sources/tech/20220613 Use Terraform to manage TrueNAS.md
Normal file
221
sources/tech/20220613 Use Terraform to manage TrueNAS.md
Normal file
@ -0,0 +1,221 @@
|
||||
[#]: subject: "Use Terraform to manage TrueNAS"
|
||||
[#]: via: "https://opensource.com/article/22/6/terraform-truenas"
|
||||
[#]: author: "Alan Formy-Duval https://opensource.com/users/alanfdoss"
|
||||
[#]: collector: "lkxed"
|
||||
[#]: translator: " "
|
||||
[#]: reviewer: " "
|
||||
[#]: publisher: " "
|
||||
[#]: url: " "
|
||||
|
||||
Use Terraform to manage TrueNAS
|
||||
======
|
||||
Get more out of TrueNAS when you integrate Terraform for configuration management.
|
||||
|
||||
![Puzzle pieces coming together to form a computer screen][1]
|
||||
|
||||
Image by: Opensource.com
|
||||
|
||||
Sometimes combining different open source projects can have benefits. The synergy of using Terraform with TrueNAS is a perfect example.
|
||||
|
||||
TrueNAS is an OpenBSD-based operating system that provides network-attached storage (NAS) and network services. One of its main strengths is leveraging the ZFS file system, which is known for enterprise-level reliability and fault tolerance. Terraform is a provisioning and deployment tool embodying the concept of infrastructure as code.
|
||||
|
||||
### TrueNAS
|
||||
|
||||
TrueNAS has a very nice web user interface (UI) for its management and an application programming interface (API). Terraform can be integrated with the API to provide configuration management of your NAS, as I'll demonstrate below.
|
||||
|
||||
To begin, I used Virtual Machine Manager to configure a virtual machine and then installed the latest version, TrueNAS 13.0. The only necessary input was to enter the root password. Once it reboots, the main menu appears. You will also see the HTTP management address. You can access this address from your local web browser.
|
||||
|
||||
![Virtual machine console setup][2]
|
||||
|
||||
### Terraform
|
||||
|
||||
Terraform needs to be installed where it can access the TrueNAS management URL. I am taking advantage of tfenv, a tool for managing Terraform versions.
|
||||
|
||||
```
|
||||
$ tfenv list-remote
|
||||
$ tfenv install 1.2.0
|
||||
$ tfenv use 1.2.0
|
||||
$ terraform -version
|
||||
Terraform v1.2.0
|
||||
on linux_amd64
|
||||
```
|
||||
|
||||
Next, create a working directory, such as `~/code/terraform/truenas`, to contain the configuration files associated with your TrueNAS instance.
|
||||
|
||||
```
|
||||
$ mkdir ~/code/terraform/truenas
|
||||
$ cd ~/code/terraform/truenas
|
||||
```
|
||||
|
||||
Create the initial terraform configuration file and add the necessary directives to define the TrueNAS provider.
|
||||
|
||||
```
|
||||
$ vi main.tf
|
||||
```
|
||||
|
||||
The provider will look like this, where the address and API key for your TrueNAS instance will need to be correctly specified.
|
||||
|
||||
```
|
||||
$ cat main.tf
|
||||
|
||||
|
||||
terraform {
|
||||
required_providers {
|
||||
truenas = {
|
||||
source = "dariusbakunas/truenas"
|
||||
version = "0.9.0"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
provider "truenas" {
|
||||
api_key = "1-61pQpp3WyfYwg4dHToTHcOt7QQzVrMtZnkJAe9mmA0Z2w5MJsDB7Bng5ofZ3bbyn"
|
||||
base_url = "http://192.168.122.139/api/v2.0"
|
||||
}
|
||||
```
|
||||
|
||||
The TrueNAS API key is created in the Web UI. Log in and click the small gear in the upper right-hand corner.
|
||||
|
||||
![A pulldown menu from settings shows options including the desired choice, API Keys][3]
|
||||
|
||||
This UI section enables you to create the API key. Once generated, copy it to the `main.tf` file.
|
||||
|
||||
### Initialize
|
||||
|
||||
In your TrueNAS Terraform directory, you have the `main.tf` file. The first step is to initialize using the command `terraform init`, which should generate the following result:
|
||||
|
||||
```
|
||||
Initializing the backend...
|
||||
|
||||
Initializing provider plugins...
|
||||
- Finding dariusbakunas/truenas versions matching "0.9.0"...
|
||||
- Installing dariusbakunas/truenas v0.9.0...
|
||||
- Installed dariusbakunas/truenas v0.9.0 (self-signed, key ID E44AF1CA58555E96)
|
||||
|
||||
Partner and community providers are signed by their developers.
|
||||
If you'd like to know more about provider signing, you can read about it here:
|
||||
https://www.terraform.io/docs/cli/plugins/signing.html
|
||||
|
||||
Terraform has created a lock file .terraform.lock.hcl to record the provider
|
||||
selections it made above. Include this file in your version control repository
|
||||
so that Terraform can guarantee to make the same selections by default when
|
||||
you run "terraform init" in the future.
|
||||
|
||||
Terraform has been successfully initialized!
|
||||
|
||||
You may now begin working with Terraform. Try running "terraform plan" to see
|
||||
any changes that are required for your infrastructure. All Terraform commands
|
||||
should now work.
|
||||
|
||||
If you ever set or change modules or backend configuration for Terraform,
|
||||
rerun this command to reinitialize your working directory. If you forget, other commands will detect it and remind you to do so if necessary.
|
||||
```
|
||||
|
||||
A successful initialization means you're ready to start adding resources. Any TrueNAS item, such as a storage pool, network file system (NFS) share, or cron job, is a resource.
|
||||
|
||||
### Add a ZFS dataset
|
||||
|
||||
The following example resource directive defines a ZFS dataset. For my example, I will add it to the `main.tf` file.
|
||||
|
||||
```
|
||||
resource "truenas_dataset" "pictures" {
|
||||
pool = "storage-pool"
|
||||
name = "pictures"
|
||||
comments = "Terraform created dataset for Pictures"
|
||||
}
|
||||
```
|
||||
|
||||
Run the command `terraform validate` to check the configuration.
|
||||
|
||||
```
|
||||
Success! The configuration is valid.
|
||||
```
|
||||
|
||||
Running `terraform plan` will describe the actions that Terraform will perform. Now, add the new dataset with `terraform apply`.
|
||||
|
||||
```
|
||||
Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
|
||||
+ create
|
||||
|
||||
Terraform will perform the following actions:
|
||||
|
||||
# truenas_dataset.pictures will be created
|
||||
+ resource "truenas_dataset" "pictures" {
|
||||
+ acl_mode = (known after apply)
|
||||
+ acl_type = (known after apply)
|
||||
+ atime = (known after apply)
|
||||
+ case_sensitivity = (known after apply)
|
||||
+ comments = "Terraform created dataset for Pictures"
|
||||
+ compression = (known after apply)
|
||||
+ copies = (known after apply)
|
||||
+ dataset_id = (known after apply)
|
||||
+ deduplication = (known after apply)
|
||||
+ encrypted = (known after apply)
|
||||
+ encryption_algorithm = (known after apply)
|
||||
+ encryption_key = (sensitive value)
|
||||
+ exec = (known after apply)
|
||||
+ generate_key = (known after apply)
|
||||
+ id = (known after apply)
|
||||
+ managed_by = (known after apply)
|
||||
+ mount_point = (known after apply)
|
||||
+ name = "pictures"
|
||||
+ pbkdf2iters = (known after apply)
|
||||
+ pool = "storage-pool"
|
||||
+ quota_bytes = (known after apply)
|
||||
+ quota_critical = (known after apply)
|
||||
+ quota_warning = (known after apply)
|
||||
+ readonly = (known after apply)
|
||||
+ record_size = (known after apply)
|
||||
+ ref_quota_bytes = (known after apply)
|
||||
+ ref_quota_critical = (known after apply)
|
||||
+ ref_quota_warning = (known after apply)
|
||||
+ share_type = (known after apply)
|
||||
+ snap_dir = (known after apply)
|
||||
+ sync = (known after apply)
|
||||
}
|
||||
|
||||
Plan: 1 to add, 0 to change, 0 to destroy.
|
||||
|
||||
Do you want to perform these actions?
|
||||
Terraform will perform the actions described above.
|
||||
Only 'yes' will be accepted to approve.
|
||||
|
||||
Enter a value:
|
||||
```
|
||||
|
||||
Type `yes` to confirm and hit Enter.
|
||||
|
||||
```
|
||||
truenas_dataset.pictures: Creating...
|
||||
truenas_dataset.pictures: Creation complete after 0s [id=storage-pool/pictures]
|
||||
|
||||
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
|
||||
```
|
||||
|
||||
That's it. You can check for this new dataset in the TrueNAS Web UI.
|
||||
|
||||
![The pictures dataset is shown in the storage pool list, with the comment "Terraform create dataset for pictures"][4]
|
||||
|
||||
### Do more with TrueNAS and Terraform
|
||||
|
||||
The TrueNAS provider for Terraform allows you to manage many more aspects of your TrueNAS device. For instance, you could share this new dataset as an NFS or server message block (SMB) share. You can also create additional datasets, cron jobs, and zvols.
|
||||
|
||||
Image by: (Alan Formy-Duval, CC BY-SA 4.0)
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
via: https://opensource.com/article/22/6/terraform-truenas
|
||||
|
||||
作者:[Alan Formy-Duval][a]
|
||||
选题:[lkxed][b]
|
||||
译者:[译者ID](https://github.com/译者ID)
|
||||
校对:[校对者ID](https://github.com/校对者ID)
|
||||
|
||||
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
|
||||
|
||||
[a]: https://opensource.com/users/alanfdoss
|
||||
[b]: https://github.com/lkxed
|
||||
[1]: https://opensource.com/sites/default/files/lead-images/puzzle_computer_solve_fix_tool.png
|
||||
[2]: https://opensource.com/sites/default/files/2022-06/TrueNAS_console.png
|
||||
[3]: https://opensource.com/sites/default/files/2022-06/TrueNAS_APIkey.png
|
||||
[4]: https://opensource.com/sites/default/files/2022-06/TrueNAS_Dataset.png
|
187
translated/tech/20210722 Write your first JavaScript code.md
Normal file
187
translated/tech/20210722 Write your first JavaScript code.md
Normal file
@ -0,0 +1,187 @@
|
||||
[#]: subject: "Write your first JavaScript code"
|
||||
[#]: via: "https://opensource.com/article/21/7/javascript-cheat-sheet"
|
||||
[#]: author: "Seth Kenlon https://opensource.com/users/seth"
|
||||
[#]: collector: "lkxed"
|
||||
[#]: translator: "lkxed"
|
||||
[#]: reviewer: " "
|
||||
[#]: publisher: " "
|
||||
[#]: url: " "
|
||||
|
||||
编写你的第一段 JavaScript 代码
|
||||
======
|
||||
JavaScript 是为 Web 而生的,但它可以做的事远不止于此。本文将带领你了解它的基础知识,然后你可以下载我们的备忘清单,以便随时掌握详细信息。
|
||||
|
||||
![开源编程][1]
|
||||
|
||||
图源:Opensource.com
|
||||
|
||||
JavaScript 是一种充满惊喜的编程语言。许多人第一次遇到 JavaScript 时,它通常是作为一种 Web 语言出现的。所有主流浏览器都有一个 JavaScript 引擎;并且,还有一些流行的框架,如 JQuery、Cash 和 Bootstrap 等,它们可以帮助简化网页设计;甚至还有用 JavaScript 编写的编程环境。它似乎在互联网上无处不在,但事实证明,它对于 [Electron][2] 等项目来说也是一种有用的语言。Electron 是一个构建跨平台桌面应用程序的开源工具包,它使用的语言就是 JavaScript。
|
||||
|
||||
JavaScript 语言的用途多到令人惊讶,它拥有各种各样的库,而不仅仅是用于制作网站。它的基础知识十分容易掌握,因此,它可以作为一个起点,助你跨出构建你想象中的东西的第一步。
|
||||
|
||||
### 安装 JavaScript
|
||||
|
||||
随着你的 JavaScript 水平不断提高,你可能会发现自己需要高级的 JavaScript 库和运行时。不过,刚开始学习的时候,你是根本不需要安装 JavaScript 的。因为所有主流的 Web 浏览器都包含一个 JavaScript 引擎来运行代码。你可以使用自己喜欢的文本编辑器编写 JavaScript,将其加载到 Web 浏览器中,接着你就能看到代码的作用。
|
||||
|
||||
### 上手 JavaScript
|
||||
|
||||
要编写你的第一个 JavaScript 代码,请打开你喜欢的文本编辑器,例如 [Notepad++][3]、[Atom][4] 或 [VSCode][5] 等。因为它是为 Web 开发的,所以 JavaScript 可以很好地与 HTML 配合使用。因此,我们先来尝试一些基本的 HTML:
|
||||
|
||||
```
|
||||
<html>
|
||||
<head>
|
||||
<title>JS</title>
|
||||
</head>
|
||||
<body>
|
||||
<p id="example">Nothing here.</p>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
保存这个文件,然后在 Web 浏览器中打开它。
|
||||
|
||||
![浏览器中显示的 HTML][6]
|
||||
|
||||
要将 JavaScript 添加到这个简单的 HTML 页面,你可以创建一个 JavaScript 文件并在页面的 `<head>` 中引用它,或者只需使用 `<script>` 标记将 JavaScript 代码嵌入 HTML 中。在这个例子中,我嵌入了下面的代码:
|
||||
|
||||
```
|
||||
<html>
|
||||
<head>
|
||||
<title>JS</title>
|
||||
</head>
|
||||
<body>
|
||||
<p id="example">Nothing here.</p>
|
||||
|
||||
<script>
|
||||
let myvariable = "Hello world!";
|
||||
|
||||
document.getElementById("example").innerHTML = myvariable;
|
||||
</script>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
在浏览器中重新加载页面。
|
||||
|
||||
![在浏览器中显示带有 JavaScript 的 HTML][7]
|
||||
|
||||
如你所见,`<p>` 标签仍然包含字符串 “Nothing here”,但是当它被渲染时,JavaScript 会改变它,使其包含 “Hello world”。是的,JavaScript 具有重建(或只是帮助构建)网页的能力。
|
||||
|
||||
这个简单脚本中的 JavaScript 做了两件事。首先,它创建一个名为 `myvariable` 的变量,并将字符串 “Hello world!” 放置其中。然后,它会在当前文档(浏览器呈现的网页)中搜索 ID 为 “example” 的所有 HTML 元素。当它找到 `example` 时,它使用了 `innerHTML` 函数将 HTML 元素的内容替换为 `myvariable` 的内容。
|
||||
|
||||
当然,我们也可以不用自定义变量。因为,使用动态创建的内容来填充 HTML 元素也是容易的。例如,你可以使用当前时间戳来填充它:
|
||||
|
||||
```
|
||||
<html>
|
||||
<head>
|
||||
<title>JS</title>
|
||||
</head>
|
||||
<body>
|
||||
<p id="example">Date and time appears here.</p>
|
||||
|
||||
<script>
|
||||
document.getElementById("example").innerHTML = Date();
|
||||
</script>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
重新加载页面,你就可以看到在呈现页面时生成的时间戳。再重新加载几次,你可以观察到秒数会不断增加。
|
||||
|
||||
### JavaScript 语法
|
||||
|
||||
在编程中,<ruby>语法<rt>syntax</rt></ruby> 指的是如何编写句子(或“行”)的规则。在 JavaScript 中,每行代码必须以分号(`;`)结尾,以便运行代码的 JavaScript 引擎知道何时停止阅读。(LCTT 译注:从实用角度看,此处的“必须”其实是不正确的,大多数 JS 引擎都支持不加分号。Vue.js 的作者尤雨溪认为“没有应该不应该,只有你自己喜欢不喜欢”,他同时表示,“Vue.js 的代码全部不带分号”。详情可以查看他在知乎上对于此问题的 [回答][10]。)
|
||||
|
||||
单词(或 <ruby>“字符串”<rt>strings</rt></ruby>)必须用引号(`"`)括起来,而数字(或 <ruby>“整数”<rt>integers</rt></ruby>)则不用。
|
||||
|
||||
几乎所有其他东西都是 JavaScript 语言的约定,例如变量、数组、条件语句、对象、函数等等。
|
||||
|
||||
### 在 JavaScript 中创建变量
|
||||
|
||||
变量是数据的容器。你可以将变量视为一个盒子,你在其中放置数据,以便与程序的其他部分共享它。要在 JavaScript 中创建变量,你可以选用关键字 `let` 和 `var` 中的一个,请根据你打算如何使用变量来选择:`var` 关键字用于创建一个供整个程序使用的变量,而 `let` 只为特定目的创建变量,通常在函数或循环的内部使用。(LCTT 译注:还有 `const` 关键字,它用于创建一个常量。)
|
||||
|
||||
JavaScript 内置的 `typeof` 函数可以帮助你识别变量包含的数据的类型。使用第一个示例,你可以修改显示文本,来显示 `myvariable` 包含的数据的类型:
|
||||
|
||||
```
|
||||
<string>
|
||||
let myvariable = "Hello world!";
|
||||
document.getElementById("example").innerHTML = typeof(myvariable);
|
||||
</string>
|
||||
```
|
||||
|
||||
接着,你就会发现 Web 浏览器中显示出 “string” 字样,因为该变量包含的数据是 “Hello world!”。在 `myvariable` 中存储不同类型的数据(例如整数),浏览器就会把不同的数据类型打印到示例网页上。尝试将 `myvariable` 的内容更改为你喜欢的数字,然后重新加载页面。
|
||||
|
||||
### 在 JavaScript 中创建函数
|
||||
|
||||
编程中的函数是独立的数据处理器。正是它们使编程得以 *模块化*。因为函数的存在,程序员可以编写通用库,例如,调整图像大小或统计时间花费的库,以供其他和你一样的程序员在他们的代码中使用。
|
||||
|
||||
要创建一个函数,你可以为函数提供一个自定义名称,后面跟着用大括号括起来的、任意数量的代码。
|
||||
|
||||
下面是一个简单的网页,其中包含了一个剪裁过的图像,还有一个分析图像并返回真实图像尺寸的按钮。在这个示例代码中,`<button>` 这个 HTML 元素使用了 JavaScript 的内置函数 `onclick` 来检测用户交互,它会触发一个名为 `get_size` 的自定义函数。具体代码如下:
|
||||
|
||||
```
|
||||
<html>
|
||||
<head>
|
||||
<title>Imager</title>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<div>
|
||||
<button onclick="get_size(document.getElementById('myimg'))">
|
||||
Get image size
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<img style="width: 15%" id="myimg" src="penguin.png" />
|
||||
</div>
|
||||
|
||||
<script>
|
||||
function get_size(i) {
|
||||
let w = i.naturalWidth;
|
||||
let h = i.naturalHeight;
|
||||
alert(w + " by " + h);
|
||||
}
|
||||
</script>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
保存这个文件,并将其加载到 Web 浏览器中以尝试这段代码。
|
||||
|
||||
![自定义的 get_size 函数返回了图像尺寸][8]
|
||||
|
||||
### 使用 JavaScript 的跨平台应用程序
|
||||
|
||||
你可以从代码示例中看到,JavaScript 和 HTML 紧密协作,从而创建了有凝聚力的用户体验。这是 JavaScript 的一大优势。当你使用 JavaScript 编写代码时,你继承了现代计算中最常见的用户界面之一,而它与平台无关,那就是 Web 浏览器。你的代码本质上是跨平台的,因此你的应用程序,无论是简单的图像大小分析器还是复杂的图像编辑器、视频游戏,或者你梦想的任何其他东西,都可以被所有人使用,无论是通过 Web 浏览器,还是桌面(如果你同时提供了一个 Electron 应用)。
|
||||
|
||||
学习 JavaScript 既简单又有趣。网络上有很多网站提供了相关教程,还有超过一百万个 JavaScript 库可帮助你与设备、外围设备、物联网、服务器、文件系统等进行交互。在你学习的过程中,请将我们的 [JavaScript 备忘单][9] 放在身边,以便记住语法和结构的细节。
|
||||
|
||||
正文中的配图来自:Seth Kenlon,CC BY-SA 4.0
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
via: https://opensource.com/article/21/7/javascript-cheat-sheet
|
||||
|
||||
作者:[Seth Kenlon][a]
|
||||
选题:[lkxed][b]
|
||||
译者:[lkxed](https://github.com/lkxed)
|
||||
校对:[校对者ID](https://github.com/校对者ID)
|
||||
|
||||
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
|
||||
|
||||
[a]: https://opensource.com/users/seth
|
||||
[b]: https://github.com/lkxed
|
||||
[1]: https://opensource.com/sites/default/files/lead-images/code2.png
|
||||
[2]: https://www.electronjs.org/
|
||||
[3]: https://opensource.com/article/16/12/notepad-text-editor
|
||||
[4]: https://opensource.com/article/20/12/atom
|
||||
[5]: https://opensource.com/article/20/6/open-source-alternatives-vs-code
|
||||
[6]: https://opensource.com/sites/default/files/pictures/plain-html.jpg
|
||||
[7]: https://opensource.com/sites/default/files/uploads/html-javascript.jpg
|
||||
[8]: https://opensource.com/sites/default/files/uploads/get-size.jpg
|
||||
[9]: https://opensource.com/downloads/javascript-cheat-sheet
|
||||
[10]: https://www.zhihu.com/question/20298345/answer/49551142
|
Loading…
Reference in New Issue
Block a user