如何在javascript中编写自己的数组方法? [英] How to write own array method in javascript?

查看:46
本文介绍了如何在javascript中编写自己的数组方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

< pre class = snippet-code-js lang-js prettyprint-override> Array.prototype.ownMethod = function(x){x(this)} [1、2、3、4] .ownMethod (function(x){return x [1]})//此回调无效。



我试图在First-class函数内部传递数组值。这种方法对我不起作用。

解决方案

您已经被自动分号插入所吸引。



函数表达式在用作属性访问器而不是数组文字之后立即创建一个对象(该函数)和方括号。



添加一个明确的语句末尾,以分号来解决。



  Array.prototype.ownMethod = function(x){x(this)}; [1、2、3、4] .ownMethod(function(x){console.log(x [1 ]);}) 


Array.prototype.ownMethod = function(x) {
  x(this)
}

[1, 2, 3, 4].ownMethod(function(x) {
  return x[1]
}) // This callback won't work .

I tried to pass array value inside my First-class function. This method won't work for me.

解决方案

You've been caught out by Automatic Semicolon Insertion.

The function expression creates an object (the function) and the square bracket immediately after it is used as a property accessor instead of an array literal.

Add an explicit end of statement with a semi-colon to fix that.

Array.prototype.ownMethod = function(x) {
  x(this)
};

[1, 2, 3, 4].ownMethod(function(x) {
  console.log(x[1]);
}) 

这篇关于如何在javascript中编写自己的数组方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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