Array.prototype.slice.call 和 slice以及call

 单独的简单介绍,后续再补上一些资料.  

 对象转换为数组.

 1 /**
 2  * slice : 数组->slice(截取)
 3  * 参数有两个,开始截取和结束截取,并返回原数组:
 4  * a.slice(1) || a.slice(1,3) => a.slice(start) || a.slice(start,[end])
 5  * 
 6  */
 7 var a = [1, 5, 7, 8, 9];
 8 var b = a.slice(1, 3);
 9 // console.log(b);
10 
11 
12 /**
13  * call:对象->call()
14  * 源于:MDN示例 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call
15  * 语法:function.call(thisArg, arg1, arg2, ...)
16  * 参数:
17  *  thisArg 可选的。注意,this可能不是方法看到的实际值:如果方法是非严格模式下的函数,null并且undefined将被全局对象替换,则原始值将被转换为对象。
18  *  arg1, arg2, ...可选的。函数的参数。
19  * 描述:
20  *  该call()允许函数/方法属于被分配并要求一个不同的对象一个对象。
21  *  call() 为 函数/方法提供了这个新值。使用  call,您可以编写一次方法,然后在另一个对象中继承它,而不必重写新对象的方法。
22  */
23 function product(name, price) {
24     this.name = name;
25     this.price = price;
26 }
27 
28 function food(name, price) {
29     product.call(this, name, price);
30 }
31 
32 console.log(new food('cheese', 6).name, 'food函数,成功调用起product的函数');
33 
34 
35 // function disInfo() {
36 //     console.log('恭喜你成功调用起call!~');
37 // }
38 // console.log(disInfo.call())
39 
40 
41 
42 function toArray() {
43     return [].slice.call(arguments);
44     // return [].slice.call(arguments,0);
45     // return Array.prototype.slice.call(arguments);
46 }
47 console.log(toArray(1, 3, 5, 6, 7));
48 
49 
50 /**
51  * Array.prototype.slice.call(arguments)能将具有length属性的对象转成数组
52  */
53 
54 var obj = {
55     length: 3,
56     0: 'a',
57     1: 'b',
58     2: 'c'
59 }
60 
61 var obj_1 = {
62     0: 'a',
63     1: 'b',
64     2: 'c'
65 }
66 
67 console.log(obj.length)

 

ES6写法:

1 //  ES6新出的方法,必须要求提供其长度,才能正确换为数组
2 let arrayLike = { 
3     '0': 'a',
4     '1': 'b', 
5     '2': 'c', 
6     length: 3 
7 };
8 console.log(Array.from(arrayLike));

 

posted @ 2018-09-21 11:13  Sunsin  阅读(304)  评论(0编辑  收藏  举报