19.1数组方法
concat
var arr1 = ['a', 'b', 'c'];
console.log(arr1);
var arr2 = ['d', 'e', 'f'];
console.log(arr2);
var arr3 = arr1.concat(arr2);
console.log(arr3);
//['a', 'b', 'c', 'd', 'e', 'f']
toString
var arr = ['a', 'b', 'c', 'd', 'e', 'f'];
console.log(arr);
//a,b,c,d,e,f
slice
var arr = ['a', 'b', 'c', 'd', 'e', 'f'];
var arr1 = arr.slice();
console.log(arr1);
//['a', 'b', 'c', 'd', 'e', 'f']
var arr2 = arr.slice(1);
//['b', 'c', 'd', 'e', 'f']
var arr3 = arr.slice(1, 3);
//['b', 'c']
var arr4 = arr.slice(-3, -1);
//['b', 'c']
join/split
split把字符串变数组
var arr = ['a', 'b', 'c', 'd'];
var str1 = arr.join();
console.log(str1);//a,b,c,d
var str2 = arr.join('');
console.log(str2);//abcd
var str3 = str2.split('');
console.log(str3);//['a', 'b', 'c', 'd']
var str4 = str2.split('', 3);
console.log(str4);//['a', 'b', 'c']
19.2类数组
function test(){
console.log(arguments);
}
test(1, 2, 3, 4, 5, 6);
arguments等类数组没有继承Array.prototype
其实是类似数组的对象
对象继承Array.protoype.splice,变成数组格式
浅紫:系统内置
深紫:用户添加
var arr = [1, 2, 3, 4, 5];
console.log(arr);
面试题
var obj = {
'2': 3,
'3': 4,
'length': 2,
'splice': Array.prototype.splice,
'push': Array.prototype.push
}
obj.push(1);
obj.push(2);
console.log(obj);
19.3应用
数组原型上写一个去重方法
var arr = [0,0,1,1,2,2,3,4,5,3,6,'a','a']
Array.prototype.unique = function(){
var obj = {},
arr = [];
for(var i = 0; i < this.length; i++){
var item = this[i];
if(!obj.hasOwnProperty(item)){
obj[item] = item;
arr.push(item);
}
}
return arr;
}
arr.unique();
字符串去重
var str = '1111222000aabb';
String.prototype.unique = function(){
var obj = {},
newStr = '';
for(var i = 0; i < this.length; i++){
var item = this[i];
if(!obj.hasOwnProperty(item)) {
obj[item] = item;
newStr += item;
}
}
return newStr;
}
str.unique();
封装typeof方法,可以返回 undefined, boolean, number, string, null, function
提示:typeof 可以返回的直接返回,
Object.prototype.toString.call() -> [object Object] [object Array] [object Number] [object Boolean] [object String]
function myTypeof(val){
var type = typeof(val);
var toStr = Object.prototype.toString;
var res = {
'[object Object]': 'object',
'[object Array]': 'array',
'[object Number]': 'object number',
'[object Boolean]': 'object boolean',
'[object String]': 'object string'
}
if(val === null) {
return 'null';
}
if(type !== 'object'){
return type;
}
var ret = toStr.call(val); // 判断引用值的类型
return res[ret];
}
console.log(myTypeof(true));
console.log(myTypeof(1));
console.log(myTypeof(new Number()));
console.log(myTypeof(null));
console.log(myTypeof(undefined));
console.log(myTypeof([]));
console.log(myTypeof({}));
console.log(myTypeof(''));