JS ARRAY
Object.keys() | Object.values()
数组 | 类数组
不管什么类型的数据 一定有个length 这个属性
类数组的原型是 Object, 数组的原型是 Array
笔试题
function test(){
console.log(typeof(arguments));
}
test() -- 打印的是 object
var test = function a(){
return 'a';
}
console.log(a) -- 报错
console.log(typeof(a)) --打印的是 undefined 函数是忽略函数名的
console.log(test.name) -- 打印的是 a 如果没有a 则打印test
类数组 根据情况赋予push 方法
类数组转化成数组的方法:var Arr = Array.prototype.slice.all(arguments);
var obj = {
'0': 1,
'1': 2,
'2': 3,
'3': 4,
'4': 5,
'5':6,
'length': 6,
'splice': Array.prototype.splice, -添加属性
‘push': Array.prototype.push;
}
Object.prototype.splice = Array.prototype.splice -- 第二种添加属性的方法
obj.push(7) - 会报错 除非继承了push 方法
用Array.prototype.fill 创建类数组
// fill 根据length 去填充相应数量的元素
const newOj = Array.prototype.fill.call({length: 3}, 4);
function makeArrayLike(arr){
var arrLike = {
length : arr.length,
push: [].push,
splice: [].splice
}
arr.forEach(function(item,index){
[].fill.call(arrLike, item, index, index+1);
})
return arrLike;s
}
const newObj = makeArrayLike{
'a','b','c','d'
}
ali恶心人的题 push的原理
var obj = {
'2': 3,
'3': 4,
'length': 2,
'splice': Array.prototype.splice, -添加属性
‘push': Array.prototype.push;
}
console.log(obj[2]) -- 打印结果 3
obj.push(1); -- obj[2] = 1 -- 原数据的'2' 会被替换掉
obj.push(2); -- obj[3] = 2
原因是因为
Array.prototype.push = function(elem){
obj[obj.length] = elem; --console.log(obj[2]) -- 打印结果 3
obj.length ++;
}
console.log(obj)
-- 打印结果 [empty x 2, 1, 2, splice:f, push:f] | 2:1 | 3:2 | length:4
\