[] .slice或Array.prototype.slice [英] [].slice or Array.prototype.slice

查看:189
本文介绍了[] .slice或Array.prototype.slice的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我心中已经遇到到阵列的原型应用到原生对象两种方式:

I’v come across both ways to apply Array prototypes to a native object:

arr = Array.prototype.slice.call(obj);
arr = [].slice.call(obj);

在类似的方式,得到了真正的类型的本地类数组对象:

In similar fashion, getting the true type of a native array-like object:

type = Object.prototype.toString.call(obj);
type = {}.toString.call(obj);

一个简单的测试:

function fn() {
    console.log(
        Array.prototype.slice.call(arguments),
        [].slice.call(arguments),
        Object.prototype.toString.call(arguments), 
        {}.toString.call(arguments)
    );
}

fn(0,1);

小提琴: http://jsfiddle.net/PhdmN/

他们似乎等同于我;第一语法用于更频繁,但第二绝对短。是否有任何缺点,使用更短的语法是什么时候?

They seem identical to me; the first syntax is used more often, but the second is definitely shorter. Are there any shortcomings when using the shorter syntax?

推荐答案

他们是相同的有关功能。

They are identical regarding functionality.

但是,阵列对象可以被覆盖,导致第一种方法失败。

However, the Array object can be overwritten, causing the first method to fail.

//Example:
Array = {};
console.log(typeof Array.prototype.slice); // "undefined"
console.log(typeof [].slice);    // "function"

字面上的方法创建的阵列(不是 Array.prototype。法)的新实例。这两种方法的基准: http://jsperf.com/bbarr-new-array- VS-文字/ 3

The literal method creates a new instance of Array (opposed to Array.prototype. method). Benchmark of both methods: http://jsperf.com/bbarr-new-array-vs-literal/3

当你要使用的方法很多次,最好的做法是缓存的方法:

When you're going to use the method many times, the best practice is to cache the method:


  • VAR片= Array.prototype.slice; //常用

  • VAR片= [] .slice; - 如果你关心阵的存在或如果你就像较短的语法。

  • var slice = Array.prototype.slice; //Commonly used
  • var slice = [].slice; - If you're concerned about the existence of Array, or if you just like the shorter syntax.

这篇关于[] .slice或Array.prototype.slice的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆