Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/spring-boot/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在javascript中将某个类的所有元素的ID放入数组_Javascript - Fatal编程技术网

在javascript中将某个类的所有元素的ID放入数组

在javascript中将某个类的所有元素的ID放入数组,javascript,Javascript,我读了,被接受的答案是: var ids = $('.cookie').map(function(index) { // this callback function will be called once for each matching element return this.id; }); 如何在纯javascript中完成上述操作?我建议如下: // using Function.prototype.call() to apply // Array.prototy

我读了,被接受的答案是:

var ids = $('.cookie').map(function(index) {
    // this callback function will be called once for each matching element
    return this.id; 
});

如何在纯javascript中完成上述操作?

我建议如下:

// using Function.prototype.call() to apply 
// Array.prototype.map() to the array-like NodeList returned
// by document.querySelectorAll():
var elementIDs = Array.prototype.map.call(document.querySelectorAll('.cookie'), function (cookie) {
  // the first argument to the anonymous function ('cookie') is
  // the array element of the array over which we're iterating,
  // and is here a DOM node.

  // here, we return the id property of the current node:
  return cookie.id;
});
参考资料:


    • 我建议如下:

      // using Function.prototype.call() to apply 
      // Array.prototype.map() to the array-like NodeList returned
      // by document.querySelectorAll():
      var elementIDs = Array.prototype.map.call(document.querySelectorAll('.cookie'), function (cookie) {
        // the first argument to the anonymous function ('cookie') is
        // the array element of the array over which we're iterating,
        // and is here a DOM node.
      
        // here, we return the id property of the current node:
        return cookie.id;
      });
      
      参考资料: