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

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

问题描述

我遇到了两种将 Array 原型应用于原生对象的方法:

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.

但是,Array 对象可以被覆盖,导致第一种方法失败.

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 的新实例(与 Array.prototype. 方法相反).两种方法的基准:http://jsperf.com/bbarr-new-array-vs-literal/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 slice = Array.prototype.slice;//常用
  • var slice = [].slice; - 如果您担心 Array 的存在,或者您只是喜欢较短的语法.
  • 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天全站免登陆