1. 程式人生 > 實用技巧 >MIT 6.828 Lab 01: Part 3

MIT 6.828 Lab 01: Part 3

陣列方法

1.陣列定義、訪問、長度

	let str = `hello`;
	console.log(str.length);//5
	console.log(str[0]);//h
	console.log(str[3]);//l
	console.log(str[str.length-1]);//o
	console.log(str.charAt(0));//h
	console.log(str.charCodeAt(0));//104

2.棧、佇列方法

	let arr = [3, 4, `hello`, true, 8];
	let val = arr.pop();//彈出
	console.log(val);//8
	console.log(arr);//[ 3, 4, "hello", true ]
	
	let arr2 = [3, 4, `hello`, true, 8];
	let val2 = arr2.push(100);//推入
	console.log(val2);//6
	console.log(arr2);//[ 3, 4, "hello", true, 8, 100 ]

	let arr3 = [3, 4, `hello`, true, 8,99];
	arr3.unshift(999);//在陣列開頭新增一個元素,也可以多個。並返回該陣列的新長度
	console.log(arr3);//[ 999, 3, 4, "hello", true, 8, 99 ]
	arr3.unshift(111,222,333);
	console.log(arr3);//[ 111, 222, 333, 999, 3, 4, "hello", true, 8, 99 ]

3.任意位置新增、刪除(會改變原陣列)

	//從1開始刪除兩個元素
	let animals = [`北極熊`,`老虎`,`獅子`,`大象`,`孔雀`];
	animals.splice(1,2);//[ "北極熊", "大象", "孔雀" ]

	//插入一個元素
	let arr = [1,3,5,`hello`,`www`];
	arr.splice(1,0,`world`);//[ 1, "world", 3, 5, "hello", "www" ]

	//替換
	let arr2 = [1,3,5,`hello`,`www`];
	arr2.splice(2,2,`world`,false);//[ 1, 3, "world", false, "www" ]

4.連線

	let arr = [4,5,6,7,8,`hello`];
	let arr2 = arr.concat();//[4,5,6,7,8,`hello`]
	let arr3 = arr.concat(111,222);//[ 4, 5, 6, 7, 8, "hello", 111, 222 ]

5.倒序、排序

revert 會改變原陣列
sort預設排序順序是將元素轉換為字元




	//需求
	//let str = `hello world` 倒過來顯示:`dlrow olleh` 如何實現?

	let str = `hello world`;
	let arr = str.split('');//將字串轉換成陣列,目的:字串不能直接替換某個值
	for(i=0;i<arr.length/2;i++){
		let temp = arr[i];
		arr[i] = arr[str.length-1-i];
		arr[str.length-1-i] = temp;
		
	}
	str = arr.join('');//"dlrow olleh"


<=>  等價於
	let str = `hello world`;
	let arr = str.split('');
	arr.reverse();
	str = arr.join('');//"dlrow olleh"

sort()

	let x = [1,30,4,21,100];
	x.sort();
	console.log(x);//[ 1, 100, 21, 30, 4 ] sort()是根據字串排序的,先比較第一位,然後比較第二位

	//排序應該這樣:
	x.sort((a,b)=>a-b);
	console.log(x);//[ 1, 4, 21, 30, 100 ]

	x.sort((a,b)=>b-a);
	console.log(x);//[ 100, 30, 21, 4, 1 ]