本文介绍了寻找一个好的清楚的解释,为什么这不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我正在学习Javascript,并在控制台中对其进行测试.任何人都可以提出一个很好的解释,为什么这样的事情不起作用?

So I am learning Javascript and testing this in the console.Can anybody come up with a good explanation why something like this does not work?

var students = ['foo', 'bar', 'baz'];

function forEach2(arr1) {
    for (i = 0; i < arr1.length; i++) {
        console.log(arr1[i]);
    }
}
students.forEach2(students)

我得到:未捕获的TypeError:students.forEach2不是一个函数

I get : Uncaught TypeError: students.forEach2 is not a function

对我来说,工作似乎合乎逻辑,但事实并非如此为什么?

For me it would seem logical to work but it doesn'twhy?

推荐答案

为使您的示例正常工作,只需在 forEach2 的定义后添加以下语句:

For your example to work, simply add the following statement after definition of forEach2:

//在这里,您将使用自己的方法重新定义内置的forEach函数.//自定义函数students.forEach = forEach2;

//现在这必须工作students.forEach(学生);

这是为什么的解释:

数组是Object的特定实现.对象是 property:value 对(例如

An array is a particular implementation of the Object. Object is an aggregate of the property:value pairs, such as

{'some_property':'1','some_function':function(),'forEach':function(){<功能逻辑>},...}

您的错误' Uncaught TypeError:students.forEach2不是一个函数'告诉您,在两者之间没有属性 forEach2 (应该是一个函数).对象的属性.因此,有两种方法可以纠正这种情况:-向对象 add 添加属性(方法函数),或更改具有类似功能的现有属性(虽然不一定).

Your error 'Uncaught TypeError: students.forEach2 is not a function' tells, that there is no property forEach2 (which supposed to be a function) in between the Object's properties. So, there are two methods to correct this situation: - add a property (method function) to the object, or alter the existing property with similar functionality (not necessarily though).

[1]第一种方法假定您使用 Array.prototype.forEach2 = function(){...} 添加新的属性函数.

[1] The first method assumes you add a new property function using Array.prototype.forEach2 = function() {...}.

[2]第二个-您可以通过为该属性分配一个新值来重新定义或更改该对象中的任何属性: Object.forEach = forEach2

[2] The second - you may redefine or alter any property in the Object by just assigning a new value to that property: Object.forEach = forEach2

这篇关于寻找一个好的清楚的解释,为什么这不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 20:16