Section 2.4 Arrays

Arrays

Array elements are numbered, starting with zero. So the first is 0. second is 1…
There are ways to defined an array.

var array = new Array;
array = [];

or we can just input the value to define the array.

var array = [0, 1, "a", "b", false]

Let’s use the array below.

var names = ['John', 'Mark', 'Alan', 'Faye']; 
var years =new Array (1969, 1948, 1989, 1990);
console.log(names);  //result (4) ["John", "Mark", "Alan", "Faye"]
console.log(names.length); //result 4
console.log(names[2]);  //result Alan. 

Add data into array

names[1] = 'Chris';
names[5] = 'Lucus';
console.log(names);//result (6) ["John", "Chris", "Alan", "Faye", empty, "Lucus"]
names[names.length] = 'Alina'; // It will always add data in the end of the array.

You can insert different type of data into array

var John = ['John', 'Li', 1991, 'designer', false]

push data value into the end of array

John.push('blue');
console.log(John);// reuslt: (6) ["John", "Li", 1991, "designer", false, "blue"] 

unshift is input the value at the begin of array

John.unshift('Mr.');
console.log(John);// result: (7) ["Mr.", "John", "Li", 1991, "designer", false, "blue"] 

shift is delete the first value of array

John.shift();
console.log(John);// result: (6) ["John", "Li", 1991, "designer", false, "blue"] 

pop is delete the last value of array

John.pop();
console.log(John);// result: (5) ["John", "Li", 1991, "designer", false] 

Once there is no sepecific value in array (23), it will return -1 which means there is no value ‘23’

console.log(John.indexOf(23)); // result: -1. 

We can use this way to define the if else statement. If a == b is true, then execute C; if a == b is false, then execute D. (Note: == compare value only; === compare value and type.)

var a === b ? " C " : " D "

Here, if John is not a designer, it will return ‘John is NOT a designer’ ; if John is a designer, it will return ‘John IS a designer’.

var isDesigner = John.indexOf('designer') === -1 ? 'John is NOT a designer' : 'John IS a designer'; 
console.log(isDesigner); //reuslt: John IS a designer
console.log(John.indexOf('designer')); // result: 3.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值