js:为什么用Array.prototype.map.call代替map() ?

js: why use Array.prototype.map.call instead of map()?

本文关键字:map call 代替 prototype 为什么 Array js      更新时间:2023-09-26

这是从casperjs JS中摘录的:

function getPrices() {
  var price = document.querySelectorAll('#InvoiceDetailGrid tbody');
  return Array.prototype.map.call(price, function(elem) {
    return elem.textContent;
  });
}

为什么使用Array.prototype.map.call:不能简单地使用:price.map() ?

因为price是一个类数组(NodeList)对象,而不是数组。

Array.prototype.map中,您使用Array的方法并使用类似数组的对象作为映射的对象。

为什么使用Array.prototype.map.call:不能简单地使用:

price.map () ?

因为您想调用作为第二个参数传入的函数,使用指定的thisthis在你的情况下是第一个参数:price, price是一个类似数组的对象(它有一个长度属性),但它没有数组的方法。因此,在像对象这样的数组中调用map函数的唯一方法是:

如果price是一个数组,则可以像通常那样调用map:

price.map(function(item){//...});

事实上,它不是一个数组路由到这个解决方案。

因为document.querySelectorAll返回一个没有.map方法的类数组对象。它不返回实际的数组