JavaScript基础-01

Posted 零陵上将军_xdr

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JavaScript基础-01相关的知识,希望对你有一定的参考价值。

javascript是一门编程语言,可为网站添加交互功能(例如:游戏、动态样式、动画以及在按下按钮或收到表单数据时作出的响应)。

JavaScript是什么?

JavaScript(缩写:JS)是一门完备的动态编程语言。当应用于html文档时,可为网站提供动态交互特性。由布兰登·艾克(Brendan Eich,Mozilla 项目、Mozilla 基金会和 Mozilla 公司的联合创始人)发明。
JavaScript 的应用场合极其广泛,简单到幻灯片、照片库、浮动布局和响应按钮点击,复杂到游戏、2D/3D 动画、大型数据库驱动程序等等。

JavaScript 相当简洁,却非常灵活。开发者们基于 JavaScript 核心编写了大量实用工具,可以使 开发工作事半功倍。其中包括:

  • 浏览器应用程序接口(api)—— 浏览器内置的 API 提供了丰富的功能,比如:动态创建 HTML 和设置 CSS 样式、从用户的摄像头采集处理视频流、生成 3D 图像与音频样本等等。
  • 第三方 API —— 让开发者可以在自己的站点中整合其他内容提供者(Twitter、Facebook 等)提供的功能。
  • 第三方框架和库 —— 用来快速构建网站和应用。

JavaScript的“Hello World”

JS代码的引入方式(与css的引入方式类似):

  1. 行内式:写在标签内部
  2. 内嵌式:写在head标签中
  3. 外链式:引入外部js文件

行内式

代码举例:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <body>
        <input type="button" value="点我点我" onclick="alert('努力学习JavaScript')" />
    </body>
</html>

分析:

  • 可以将单行或少量JS代码写在HTML标签的事件属性中(以on开头的属性),比如放在上面的onclick 点击事件中。
  • 这种书写方式,不推荐使用,原因是:可读性差,尤其是需要编写大量 JS 代码时,很难维护;引号多层嵌套时,也容易出错。
  • 关于代码中的「引号」,在 HTML 标签中,我们推荐使用双引号,JS 中我们推荐使用单引号。

内嵌式

我们可以在HTML页面中的 标签里放入并在<script>里面书写 JavaScript代码

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <script type="text/javascript">
        // 在这里写 js 代码
        alert('努力学习JavaScript');
        console.log('引入JavaScript 方式2');
    </script>
</body>

分析:

  1. text表示纯文本,因为JavaScript
  2. 可以将多行JS代码写到

外链式

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
     <!-- 外链式:引入外部的 js 文件:这个 utils.js 文件与当前的 html 文件,处于同一级目录 -->
     <script src="utils.js"></script>
</body>
</html>

分析:

  • 上面这段代码,依然是放到 body 标签里,可以和内嵌的 JS 代码并列。
  • 上方代码的 script 标签已经引入了外部 JS 文件,所以这个标签里面,不可以再写 JS 代码。

总结:
我们在实战开发中,基本都是采用方式外链式,因为将 html 文件和 js 文件分开的方式,有利于代码的结构化和复用,符合高内聚、低耦合的思想。很少会有人把一大堆 JS 代码塞到 html 文件里。

关于window.onload:先加载,最后执行

上面的三种方式,有个共同的地方是:JS代码都是写在中的,准确来说,是在页面标签元素的后面,在body结束标签的前面。
为什么一般是按照这样的顺序来写呢? 这是因为:浏览器默认会从上至下解析网页。当你需要通过JS来操作界面上的标签元素的时候,假如将JS代码、

<head>
  window.onload = function()
    // 这里可以写操作界面元素的JS代码,等页面加载完毕后再执行
    ...
  
</head>

window.onload的含义是:等界面上所有内容都加载完毕后(不仅要等文本加载完毕,而且要等图片也要加载完毕),再执行中的代码。做到了先加载,最后执行,也就是:等页面加载完毕后再执行。
当然,我们可以根据具体需求,将 window.onload 写在 标签中,或者写在

JavaScript一些简单的语法规则

学习程序,是有规律可循的,程序会有有相同的部分,这些部分就是一种规定,不能更改,我们称之为:语法。我们先来了解一个简单的语法规则。

1、JS对换行、缩进、空格不敏感。每一条语句以分号结尾。

<script type="text/javascript">
    alert("今天我想加班了");
    alert("今天天气不错啊");
</script>
<script type="text/javascript">
    alert("今天我想加班了");alert("今天天气不错啊");
</script>

上面两端代码是等价的

2、每一条语句末尾都要加上分号。虽然分号不是必须加的,但如果不加分号,浏览器会自动添加分号,导致消耗一些系统资源和性能,甚至有可能添加错误
3、所有的符号都是英文的。比如括号、引号、分号
4、JS严格区分大小写

前端代码注释

注释:即解释、注解。注释有利于提高代码的可读性,且有利于程序员之间的沟通。
注释可以用来解释某一段代码的功能和作用;通过注释,还可以补充代码中未体现出来的部分。
注释可以是任何文字,可以写中文。

HTML的注释

格式:

<!-- 我是 HTML 注释  -->

举例:

<!--头部开始-->
<div class="header"></div>
<!--头部结束-->
<!--内容开始-->
<div class="main"></div>
<!--内容结束-->
<!--底部开始-->
<div class="footer"></div>
<!--底部结束-->

CSS注释

举例:

<style type="text/css">
    /* 我是 CSS 注释 */
    p 
        font-weight: bold;
        font-style: italic;
        color: red;
    
</style>

注意:CSS 只有/* */这种注释,没有//这种注释。而且注释要写在

JavaScript的注释

单行注释:

// 我是注释

多行注释:

/*
        多行注释1
        多行注释2
*/

补充:VS Code 中,单行注释的快捷键是「Ctrl + /」,多行注释的默认快捷键是「Alt + Shift + A」。
当然,如果你觉得多行注释的默认快捷键不方便,我们还可以修改默认快捷键。操作如下:
VS Code --> 首选项 --> 键盘快捷方式 --> 查找“注释”这两个字 --> 将原来的快捷键修改为其他的快捷键,比如「Ctrl + Shift + /」。

JavaScript输出语句:

弹窗:alert()语句

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <body>
        <script>
            alert('零陵上将军邢道荣');
        </script>
    </body>
</html>

alert(英文翻译为“警报”)的用途:弹出“警告框”。它会在弹窗中显示一条信息,并等待用户按下 “OK”。
上面的代码中,如果写了两个 alert()语句,则网页的效果是:弹出第一个警告框,点击确定后,继续弹出第二个警告框。

弹窗:confirm()语句(含确认/取消)

代码运行后,页面上会显示一个弹窗。弹窗上有“确认”和“取消”两个按钮,点击“确定”返回 true,点击“取消”返回 false。

弹出输入框:prompt()语句

prompt()就是专门弹出能够让用户输入的对话框。用得少,测试的时候偶尔会用。

var a = prompt('请随便输入点什么东西吧');
console.log(a);

上方代码中,用户输入的内容,将被传递到变量 a 里面,并在控制台打印出来。

alert()和prompt()的区别:

  • alert() 语句中可以输出数字和字符串,如果要输出字符串,则必须用引号括起来;prompt()语句中,用户不管输入什么内容,都是字符串。
  • prompt() 会返回用户输入的内容。我们可以用一个变量,来接收用户输入的内容。

网页内容区域输出:document.write()语句
代码举例:

document.write('说出吾名吓汝一跳');

控制台输出:console.log()打印日志

console.log()表示在控制台中输出。console 表示“控制台”,log 表示“输出”。括号里可以写字符串、数字、变量。
控制台是程序员调试程序的地方,比如使用 console 语句打印日志,测试程序是否运行正常。
在 Chrome 浏览器中,按 F12 即可打开控制台,选择「console」栏,即可看到打印的内容。

console 语句可以设置不同的打印等级:

console.log('说出吾名'); //普通打印
console.warn('吓汝一跳'); //警告打印
console.error('我乃零陵上将军邢道荣'); //错误打印

上图中,不同的打印等级,区别不大,只是颜色背景上的区别,方便肉眼区分、过滤信息。
做前端开发时需要经常使用控制台做调试,我们甚至可以直接在控制台输入 JS 语句,然后打印执行结果。

总结:alert() 主要用来显示消息给用户,console.log() 用来给程序员做调试用。

javascript JAVASCRIPT基础

/////////////////////////////////////////////////////////////////////////
// DEFAULT OBJECTS

> window.innerHeight
217
> window.innerWidth
1704
> navigator.vendor
"Google Inc."

(there are many more)

#####
# define your own objects and access properties

var student1 = {
    fullName:'John Doe',
    age: 23,
    city: 'New York',
    ssn: "11-22-33-44" // no comma at the end of the last property
}                      // declaration
Accessing an object's properties: we use the operator "."

> student1.ssn
"11-22-33-44"
> student1.age
23
> student1
[object Object] {
    age: 23,
    city: "New York",
    fullName: "John Doe",
    ssn: "11-22-33-44"
}

/////////////////////////////////////////////////////////////////////////
// ARRAYS


// Initialize array
var daysOfWeek = [];

// accessing elements
> var daysOfWeek = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
undefined
> daysOfWeek[0]
"Monday"
> daysOfWeek[1]
"Tuesday"
> daysOfWeek[2]
"Wednesday"
> daysOfWeek.length
7

// length property
> var daysOfWeek = ['Monday', 'Tuesday', 'Wednesday', 'Thursday','Friday', 'Saturday', 'Sunday'];
undefined
> daysOfWeek.length
7

// adding elements using new index
> var daysOfWeek = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
undefined
> daysOfWeek.length
6
> daysOfWeek[6]
undefined
// NO ELEMENT AT INDEX 6 in an array of 6 elements, first index is 0 // last 6-1 = 5
> daysOfWeek[6] = 'Sunday'
"Sunday"
> daysOfWeek.length
7


// arrays are js objects
> var a = [];
> typeof a;
"object"
> var a = [1,2,3];
> a
[1, 2, 3]
> a[0]
1
> a[1]
2

// add element using push
> var daysOfWeek = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
undefined
> daysOfWeek.length
6
> daysOfWeek.push('Sunday');
7
> daysOfWeek
["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
> daysOfWeek.length
7

// strings as arrays
> var s = 'one';
> s[0]
"o"
> s[1];
"n"
> s[2];
"e"
> s.length;
3
//const kelvin = 294;
const kelvin = prompt('What is the Kelvin temperature today?')
let celsius = kelvin - 273;

/* Calculation */
let fahreneit = celsius * (9/5) + 32
fahreneit = Math.floor(fahreneit)
console.log(`The temperature is ${fahreneit} degrees fahreneit`)



///////////////////////////////////////

//Global variables are variables declared outside of functions. They can be used anywhere in the code.
var x = 1;

// global scope
function f1() {
  console.log(x); // displays '1' in devtool console
}

f1();

###

var a = 1; // global variable

function f() {
  if (true) {
    // this is a block, defined by "{" and "}"
    var a = 4; // this "a" is NOT local to the block
  }

  alert(a); // alerts '4', not the global value of '1'
            // a variable declared with "var" in a 
            // function is local to the f
			
###

var x = 1; // global variable, could be "masked" by local variables

function f2(x) {
  console.log(x); // displays the given argument  
                  // not the global value of x (value = 1)
                  // the x parameter acts as a variable
                  // local to the function, that "masks"
                  // the global variable x
}

f2(3); // will display 3

// local scope again
function f3() {
  var x = 4;      // local variable, scope = the function
  console.log(x); // displays '4'. The local variable x
                  // "masks" the global variable x
}

f3(); // will display '4' 


###

// local scope again, but mistake! We forgot var
// when declaring the local variable x
// -> same as declaring a global function var x = 3; 
function f3() {
  x = 3;      // mistake, we forgot "var"
              // x is no more a local variable, 
              // x is now global!
  var y = 5;  // real local variable
  console.log(x); // displays '3'. 
}

function f4() {
  console.log(x); // will display 3 even if there is no
                  // global declaration var x outside of 
                  // functions. The error in the declaration of x
                  // in f3 has made x global
}

function f5() {
  console.log(y); // error, no global variable y
}

f3(); // displays 3
f4(); // displays 3, x declared without var in f3
      // is considered global, and usable in f4

f5(); // error, y is a variable local to the f3 function

###


var a = 1; // global variable

function f() {
  if (true) {
    // this is a block, defined by { and }
    let a = 4; // this "a" IS LOCAL TO THE BLOCK
  }

  alert(a); // alerts '1', a is the global variable
            // a variable declared with "let" in a 
            // block is local to the block!
            // and is not defined anywhere else
            // The a defined in the if block is not
            // visible here, so the a we have here
            // is the "global" a!
}
////////////////////////////////////////////////
// Functions
let calculatorIsOn = false;

const pressPowerButton = () => {
  if (calculatorIsOn) {
    console.log('Calculator turning off.');
    calculatorIsOn = false;
  } else {
    console.log('Calculator turning on.');
    calculatorIsOn = true;
  }
};

pressPowerButton();
// Output: Calculator turning on.

pressPowerButton();
// Output: Calculator turning off.

// Functions with parameters:
const multiplyByThirteen = (inputNumber) => {
  console.log(inputNumber * 13);
};

multiplyByThirteen(9);
// Output: 117

const takeOrder = (topping) => {
  console.log(`Order: pizza topped with ${topping}`)
   
};

takeOrder('pineapple');



// Functions with multiple parameters
const getAverage = (numberOne, numberTwo) => {
  const average = (numberOne + numberTwo) / 2 ;
  console.log(average);
};

getAverage(365, 27);
// Output: 196


const takeOrder = (topping, crustType) => {
  console.log(`Order: ${crustType} pizza topped with ${topping}`)
   
};

takeOrder('pineapple', 'cheese');
takeOrder('pineapple', 'cheese');
takeOrder('pineapple', 'cheese');

// Functions with return
const getAverage = (numberOne, numberTwo) => {
  const average = (numberOne + numberTwo) / 2;
  return average;
}

console.log(getAverage(365, 27));
// Output: 196


let orderCount = 0;

const takeOrder = (topping, crustType) => {
  console.log(`Order: ${crustType} pizza topped with ${topping}`)
  orderCount++;
   
};

const getSubTotal = (itemCount) => {
  return itemCount * 7.5
}

takeOrder('pineapple', 'cheese');
takeOrder('pineapple', 'cheese');
takeOrder('pineapple', 'cheese');

console.log(getSubTotal(orderCount))

//
const multiplyByNineFifths = (celsius) => {
  return celsius * (9/5);
};

const getFahrenheit = (celsius) => {
  return multiplyByNineFifths(celsius) + 32;
};

console.log('The temperature is ' + getFahrenheit(15) + '°F');
// Output: The temperature is 59°F

//////

let orderCount = 0;

const takeOrder = (topping, crustType) => {
  console.log(`Order: ${crustType} pizza topped with ${topping}`)
  orderCount++;
   
};

const getSubTotal = (itemCount) => {
  return itemCount * 7.5
}

const getTax = (orderCount) => {
  return getSubTotal(orderCount) * 0.06
}

const getTotal = () => {
  return getSubTotal(orderCount) + getTax(orderCount)
}

takeOrder('pineapple', 'cheese');
takeOrder('pineapple', 'cheese');
takeOrder('pineapple', 'cheese');

console.log(getSubTotal(orderCount));
console.log(getTotal());

///// UP TO HERE WE HAVE SEEN ONLY "ARROW FUNCTION SYNTAX" FOR DECLARING Functions

// MORE ON FUNCTION DECLARATIONS

// Standard function declaration
function square (number) {
  return number * number; 
}

console.log(square(5));
// Output: 25.

function isGreaterThan(numberOne, numberTwo){
	if (numberOne > numberTwo){
    return true;
  } else {
    return false;
  }
}

isGreaterThan(4, 6)

//A function expression is similar to function declaration, with the exception that identifier can be omitted, creating an anonymous function. Function expressions are often stored in a variable. You can identify a function expression by the absence of a function name immediately trailing the function keyword.

// THE ARROW SYNTAX IS A SHORTER VERSION OF THIS

const square = function (number) {
  return number * number;
};

console.log(square(5));
// Output: 25.

const isGreaterThan = (numberOne, numberTwo) =>{
	if (numberOne > numberTwo){
    return true;
  } else {
    return false;
  }
}

isGreaterThan(4, 6)

// Ways to write arrow functions
const multiplyByNineFifths = celsius => celsius * (9/5);

const getFahrenheit = celsius => multiplyByNineFifths(celsius) + 32;

console.log('The temperature is ' + getFahrenheit(15) + '°F');
You'll notice:

//The parentheses around celsius have been removed, since it is a single parameter.
//The return keyword has been removed since the function consists of a single-line block.
//The {} have been removed, again, since the function consists of a single-line block.


////////////////////////////////////////////////////////


function sum(a, b) {
    var c = a + b;
    return c;
}

# Calling it
var result = sum(1, 2);
//result is equal to 3
console.log(result)
> 3

// Function parameters
If parameters are omitted during the call, JavaScript gives them the value undefined:

> sum(1)
NaN

// Functions with a variable number of parameters
An array named "argument" is created automatically in each function, it contains all the call parameters of the function:

function f() {
   return arguments;
}
...
f();
// returns []
...
f( 1, 2, 3, 4, true, 'Michel Buffa');
// returns [1, 2, 3, 4, true, "Michel Buffa"]


//function newSum() {
    var i, res = 0;
    var numberOfParameters = arguments.length;
    for (i = 0; i < numberOfParameters; i++) {
       res += arguments[i];
    }
    return res;
}
...
>>> newSum(1, 1, 1);
3
>>> newSum(1, 2, 3, 4);
10
/////////////////////////////////////////////
// Mathematical assignment

// Assignment
let x = 4;
x += 2; // x equals 6

let y = 4;
y -= 2; // y equals 2

let z = 4;
z *= 2; // z equals 8

let r = 4;
r++; // r equals 5

let t = 4;
t--; // t equals 3

// Incremental
let r = 4;
r++;
r--;


// Simple
let x = 4;
let y = 5;
let z = x * y;


////////////////////////////////////////////////////////
// POST INCREMENT AND PRE INCREMENT

> var a = 123; var b = a++;
undefined
 
> b;
123
 
> a;
124
 
> var a = 123; var b = ++a;
undefined
 
> b;
124
 
> a;
124
 
> var a = 123; var b = a--;
undefined
 
> b;
123
 
> a;
122
# Variables 

Variables are handled by const, let

// This line of code sets the variable location to the string New York City
// Constant
// Change the value of a constant will give: 
//		TypeError: Assignment to constant variable.
const location = 'New York City';

// This line of code sets the variable latitude to the number 40.7
let latitude = 40.7;
latitude = 30.3;

// This line of code sets the variable inNorthernHemisphere to true
let inNorthernHemisphere = true;

console.log(location) /* prints location value */

// Variables with no value = undefined
let whatAmI;

// Constant Variables (If we try to assign value to them they ll throw error)
var TIME_LIMIT;
 
// ES2015 Syntax
const MAX_GRADE = 20;

const Panos = 20;
undefined
Panos = 30
VM145:1 Uncaught TypeError: Assignment to constant variable.
    at <anonymous>:1:7
    
////////////////////////////////////////////////////////
// WEAKLY AND STRONGLY TYPED VARIABLES

//When we have to declare the type of variable upon declaration
ie like in C# int x = 2; (Strongly typed)

When we dont have to declare the type of variable, like JS
let x = 2; 


/////////////////////////////////////////////////////////
// DATA TYPES

// Primitive (var, string, etc)
var x = 3; var name = "Buffa";

// Objects
var michel = { firstName:'Michel', lastName:'Buffa' }
var person = {name:'panos', lastname:'doul'}
undefined
typeof person
"object"
console.log(person.name)
VM760:1 panos
undefined
console.log(person.lastname)
VM768:1 doul
undefined


// Predefined objects (arrays, fashion)
number: 1, 2, 3...
string: 'a', "one", 'two', 'World Wide Web' ..
boolean: true / false
null: empty
///////////////////////////////////////////////////////////
//The concatenation operator (+)
//The operator (+) used with strings is called the concatenation operator, and it allows you to concatenate strings.
//the operator (+)
var s1 = 'one';
var s2= 'two';
var s = s1 + s2;
s;
// returns 'onetwo'
typeof s;
//'string'


//////////////////////////////////////////////////////////
//The shorthand assignment operator (+=)
//The shorthand assignment operator (+=) can also be used to concatenate strings.
//the assignment operator (+=)
var s1 = 'one';
var s2 = 'two';
s1+= s2; // or directly s1+='two'
s1;
//returns 'onetwo'

///////////////////////////////////////////////////////////
//The method concat()
//Another way to concatenate strings is the method concat().

//the 'concat' method
var s1 = 'one';
var s2 ='two';
var s = s1.concat(s2);
s;
//returns 'onetwo'


///////////////////////////////////////////////////////////
// Concatenation
//All the methods shown above can be used with a variable number of arguments:

var s1 = 'Hello';
s1 = s1 + ' World' + ' JavaScript';
var s2 = 'Hello';
s2+= ' World' + ' JavaScript';
var s3 = 'Hello';
s3.concat(' World' , ' JavaScript' );
//s1,s2 and s3 return 'Hello World JavaScript'


////////////////////////////////////////////////////////////
// Converting strings

Converting strings
A String number in an arithmetic expression is converted to Number, unless the formula is a pure addition.

> var s = '1'; s = 3 * s; typeof s;
"number"
 
> s;
3
 
> var s = '1'; s++; typeof s;
"number"
 
> s;
2
 
> var s = "100"; typeof s;
"string"
 
> s = s * 1;
100
 
> typeof s;
"number"
 
> var d = "101 dalmatians";
undefined
 
> d * 1;
NaN


///////////////////////////////////////////////////////
//How to convert a Number into a String
//There is trick for converting a Number into a String: we 
//concatenate with an empty string, at the beginning of expression (type this in the devtools):

var n = 1;
typeof n;
// returns "number"
n = "" + n;
// returns "1"
typeof n;

///////////////////////////////////////////////////////
//Special character: the "\"
//The \ is useful for "escaping" special characters. Here are a few examples:

var s = 'I don\'t know';
var s = "I don\'t know"; // here the \ is useless
var s = "I don't know";  // same result as previous line
var s = '"Hello", he said.'; // ok, double quotes inside single one will be displayed
var s = "\"Hello\", he said."; // double quotes inside double quotes need to be escaped
// returns "string"


////////////////////////////////////////////////////////
// Escaping the escape! Use a double "\"
var s = "1\\2"; s;
// returns "1\2"


///////////////////////////////////////////////////////
// Special characters starting with "\"
"\n" for "next line":
var s = '\n1\n2\n3\n';
s
// returns "
1
2
3
"


///////////////////////////////////////////////////////
// Carriage return

"\r" for "carriage return":
var s = '1\r2';
var s = '1\n\r2';
var s = '1\r\n2';
// the three previous lines give :
"1
2"

///////////////////////////////////////////////////////////
// tab
// var s = "1\t2"
// s is equal to
"1 2"


///////////////////////////////////////////////////////////
// Substring
var string1 = "panagos";
undefined
var res = string1.substr(1, 4);
undefined
res
"anag"
var res = string1.substring(1, 4);
undefined
res
"ana"

////////////////////////////////////////////////
// Iterators 
// ForEach - iterate over array using iterator
let artists = ['Picasso', 'Kahlo', 'Matisse', 'Utamaro'];

artists.forEach(function(artist) {
  console.log(artist + ' is one of my favorite artists.');
});

let numbers = [1, 2, 3, 4, 5];

// map - apply a function to an array
let squareNumbers = numbers.map(function(number) {
  return number * number;
});

console.log(squareNumbers);

// filter - filter out of array
let things = ['desk', 'chair', 5, 'backpack', 3.14, 100];

let onlyNumbers = things.filter(function(thing) {
  return typeof thing === 'number';
});

console.log(onlyNumbers);

//// For each
// iterate over array - method 1 multi line
let fruits = ['mango', 'papaya', 'pineapple', 'apple'];

// Iterate over fruits below
fruits.forEach(function(fruit){
               console.log('I want to eat a ' + fruit)
               });
			   
// Iterate over array - single liner
let fruits = ['mango', 'papaya', 'pineapple', 'apple'];

// Iterate over fruits below
fruits.forEach(fruit => console.log('I want to eat a ' + fruit));

///// Map
/////////////////////////////////////////////
// LOOPS

// iterate over array with index
let vacationSpots = ['Mozambique', 'Thailand', 'Bolivia'];


for (let vacationSpotIndex = 0; vacationSpotIndex < vacationSpots.length; vacationSpotIndex++){
  console.log(vacationSpots[vacationSpotIndex]);
}

// backwards for loop (countdown)
let vacationSpots = ['Mozambique', 'Thailand', 'Bolivia'];


for (let vacationSpotIndex = vacationSpots.length - 1; vacationSpotIndex >= 0; vacationSpotIndex--){
  console.log('I would love to visit ' + vacationSpots[vacationSpotIndex]);
}

// Nested for loops - comparing two arrays (make into function)
for (let i = 0; i < myArray.length; i++) {
  for (let j = 0; j < yourArray.length; j++) {
    //Code To Run
   }
 }
 
 
let myPlaces = ['petra', 'andros', 'mykonos'];
let friendPlaces = ['1', '2', 'andros'];

for (let myPlacesIndex = 0; myPlacesIndex < myPlaces.length; myPlacesIndex++){
  	
  for (let friendPlacesIndex = 0; friendPlacesIndex < friendPlaces.length; friendPlacesIndex++)		{
    	if (myPlaces[myPlacesIndex] === friendPlaces[friendPlacesIndex]){
        console.log(myPlaces[myPlacesIndex]);
      }
  }
}

// while loops
while (condition) {
  // Code block that loops until condition is false
}

let cards = ['Diamond', 'Spade', 'Heart', 'Club'];
let currentCard = 'Heart';

while (currentCard !== 'Spade'){
  console.log(currentCard);
  currentCard = cards[Math.floor(Math.random()*4)];
}

console.log('found a spade')

// Infinite loops in JS

// Initiate an infinite loop
while (true) {
    // execute code forever
}

for (let i = 0; i < array.length; i--) {
   //some code
}

// break out with condition
let flag = true;
let counter = 0;
while(flag === true){
  console.log(counter);
  counter+=1;
  if (counter === 37){
    break;
  }
}

console.log(bucketList);

// Indexing in arrays and calling on elements
let newYearsResolutions = [ "panos", "penos", "pinos"];
console.log(newYearsResolutions)

let listItem = newYearsResolutions[0];
console.log(listItem);
console.log(newYearsResolutions[2]);
console.log(newYearsResolutions[3]); //undefined

// Assigning value to an element
let newYearsResolutions = [ "panos", "penos", "pinos"];
console.log(newYearsResolutions)

let listItem = newYearsResolutions[0];
console.log(listItem);
console.log(newYearsResolutions[2]);
console.log(newYearsResolutions[3]);

newYearsResolutions[1] = "Learn a new language";
console.log(newYearsResolutions)

// Length of array
let newYearsResolutions = [ "panos", "penos", "pinos"];
console.log(newYearsResolutions)

let listItem = newYearsResolutions[0];
console.log(listItem);
console.log(newYearsResolutions[2]);
console.log(newYearsResolutions[3]);

newYearsResolutions[1] = "Learn a new language";
console.log(newYearsResolutions);
console.log(newYearsResolutions.length);

// Push and Pop
let newYearsResolutions = [ "panos", "penos", "pinos"];
console.log(newYearsResolutions)

let listItem = newYearsResolutions[0];
console.log(listItem);
console.log(newYearsResolutions[2]);
console.log(newYearsResolutions[3]);

newYearsResolutions[1] = "Learn a new language";
console.log(newYearsResolutions);
console.log(newYearsResolutions.length);

newYearsResolutions.push("pinis", "panas");
console.log(newYearsResolutions);


newYearsResolutions.pop();
console.log(newYearsResolutions);

// Shift, Unshift
let groceryList = ['orange juice', 'bananas', 'coffee beans', 'brown rice', 'pasta', 'coconut oil', 'plantains'];

groceryList.shift();
console.log(groceryList);

// Slice / Substring
let groceryList = ['orange juice', 'bananas', 'coffee beans', 'brown rice', 'pasta', 'coconut oil', 'plantains'];

groceryList.shift();
console.log(groceryList);

groceryList.unshift("popcorn");
console.log(groceryList);


// Constant and normal arrays
You may recall that you can declare variables with both the let and const keywords. Variables declared with let can be reassigned.

Variables that are assigned with const cannot be reassigned. However, arrays that are declared with const remain mutable, or changeable.
let condiments = ['Ketchup', 'Mustard', 'Soy Sauce', 'Sriracha'];

const utensils = ['Fork', 'Knife', 'Chopsticks', 'Spork'];

condiments.push('Icecream');

console.log(condiments);

condiments = ['panos'];
console.log(condiments);

utensils.pop();
console.log(utensils);

utensils = ['spoon'];
console.log(utensils);

console.log(groceryList.slice(1, 4));


groceryList.unshift("popcorn");
console.log(groceryList);
///////////////////////////////////////
// SCOPE

// GLOBAL VARS
const satellite = 'The Moon';
const galaxy = 'The Milky Way';
let stars = 'North Star';

const myNightSky = () => {
  return 'Night Sky: ' + satellite + ', ' + stars + ', ' + galaxy;
}

console.log(myNightSky());

// Unexpectedly chaning the values of blobal vars inside a functionconst satellite = 'The Moon';
const galaxy = 'The Milky Way';
let stars = 'North Star';

const myNightSky = () => {
  stars = 'Sirius';
  return 'Night Sky: ' + satellite + ', ' + stars + ', ' + galaxy;
}

console.log(myNightSky());
console.log(stars)

// variables defined in block scope are not accessible outside of it - will give reference error
const colorOfSky = () => {
  let color = 'blue'; 
  console.log(color); // blue 
};

colorOfSky(); // blue 
console.log(color); // undefined

// scope of variables defined in if block
const visibleLightWaves = () => {
  let lightWaves = 'Moonlight';
  let region = 'The Arctic';
  if (region === 'The Arctic'){
    let lightWaves = 'Northern Lights';
    console.log(lightWaves)
  }
  console.log(lightWaves)
}

visibleLightWaves();


// Scope in a for loop
const cloudCount = () => {
  let i = 2;
  console.log(i); // 2
  for (let i = 0; i < 10; i++) {
    console.log(i); // All numbers from 0 to 9
  }
};

cloudCount();
console.log(i); // undefined
//////////////////////////////////////////////////
// Control flows

// Ex:
// '', false are negatives
//All variables that have been created and set are truthy (and will evaluate to true if they are the condition of a control flow statement) unless they contain one of the seven values listed below:

//false
//0 and -0
//"" and '' (empty strings)
//null
//undefined
//NaN (Not a Number)
//document.all (something you will rarely encounter)

let userName = '';
let knowsJavaScript = false;

if (knowsJavaScript && userName) {
  console.log('Great, ' + userName + '! Get ready to practice your JavaScript!');
} else if (knowsJavaScript) {
  console.log('Great! Get ready to practice your JavaScript!');
} else if (userName) {
  console.log('Great, ' + userName + '! Get ready to learn something new!');
} else {
  console.log('Great! Get ready to learn something new!');
}

// The negation of a condition
let isPhoneCharged = true; 
if (!isPhoneCharged) {
  console.log('Plug in your phone!');
} else {
  console.log('No need to charge!');
}

// Math comparison operators
// <, >, <=, >=, ===, !==
let hungerLevel = 10;

if (hungerLevel > 7) {
  console.log('Time to eat!')
} else {
  console.log('We can eat later!')
}

// String comparison
let moonPhase = 'full';

if (moonPhase == 'full'){
  console.log('Howl');
} else {
  console.log('I swear I am not a werewolf.')
}

// if / elseif
let stopLight = 'green';

if (stopLight === 'red') {
  console.log('Stop');
} else if (stopLight === 'yellow') {
  console.log('Slow down');
} else if (stopLight === 'green') {
  console.log('Go!');
} else {
  console.log('Caution, unknown!');
}

// Logical operators
if (stopLight === 'green' && pedestrians === false) {
  console.log('Go!');
} else {
  console.log('Stop');
}

let moonPhase = 'full';
let isFoggyNight = false;

if (moonPhase === 'full' || isFoggyNight){
  console.log('Howl');
} else if (moonPhase === 'mostly full'){
  console.log('Arms and legs are getting hairier');
} else if (moonPhase === 'mostly new'){
  console.log('Back on two feet');
} else {
  console.log('Invalid moon phase');
}

// Swich statements

let groceryItem = 'papaya';

switch (groceryItem) {
  case 'tomato':
    console.log('Tomatoes are $0.49');
    break;
  case 'lime':
    console.log('Limes are $1.49');
    break;
  case 'papaya':
    console.log('Papayas are $1.29');
    break;
  default:
    console.log('Invalid item');
    break;
}

let moonPhase = 'full';




switch (moonPhase) {
  case 'full':
    console.log('Howl');
    break;
  case 'mostly full':
    console.log('Arms and legs are getting hairier')
    break;
  case 'mostly new':
    console.log('Back on two feet')
    break;
  default:
    console.log('Invalid moon phase')
    break;
 
   
  }
  
  
// the ternary operators
ge >= 16 ? console.log('You are old enough to drive in the United States!') : console.log('You are not old enough to drive in the United States!');

let isLocked = false;

isLocked ? console.log('You will need a key to open the door.') : console.log('You will not need a key to open the door.');


let isCorrect = true;

isCorrect ? console.log('Correct!'):
  console.log('Incorrect!');


let favoritePhrase = 'Love That!';

favoritePhrase === 'Love That!' ?
  console.log('I love that!'):

  console.log("I don't love that!");
////////////////////////////////////////////////
// String interpolation


let favoriteAnimal = 'Koala';
console.log('My favorite animal: ' + favoriteAnimal)

let favoriteAnimal = 'Koala';
let combined = 'Koala' + favoriteAnimal;
console.log('My favorite animal: ' + favoriteAnimal)
console.log(combined)

// 2nd way
let myName = 'George';
let myCity = 'NY';

console.log(`My name is ${myName}. My favorite city is ${myCity}.`)
/////////////////////////////////////////////
// Print on console
console.log('string')
console.log('string'.toUpper())
console.log(Math.random() * 100)
/////////////////////////////////////////////
// Comments 

Comments in JS are initiated with "//" (Single Line)
Multiline comments are handled with /* */

以上是关于JavaScript基础-01的主要内容,如果未能解决你的问题,请参考以下文章

JavaScript基础入门01

JavaScript基础复习01-JavaScript,变量,数据类型,类型转换

javascript基础01

JavaScript自己整理的基础-01

JavaScript基础-01

Javascript基础思维导图01