JavaScript 是否支持像 Python 那样的数组/列表推导式?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31353213/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 09:51:44  来源:igfitidea点击:

Does JavaScript support array/list comprehensions like Python?

javascriptpython

提问by A K

I'm practicing/studying both JavaScript and Python. I'm wondering if Javascript has the equivalence to this type of coding.

我正在练习/学习 JavaScript 和 Python。我想知道 Javascript 是否与这种类型的编码等效。

I'm basically trying to get an array from each individual integer from the string for practice purposes. I'm more proficient in Python than JavaScript

我基本上试图从字符串中的每个单独的整数中获取一个数组以用于练习目的。我比 JavaScript 更精通 Python

Python:

Python:

string = '1234-5'

forbidden = '-'

print([int(i) for i in str(string) if i not in forbidden])

Does Javascript have something similar for me to do above?

Javascript 是否有类似的事情让我在上面做?

采纳答案by DRD

Update:Array comprehensions were removed from the standard. Quoting MDN:

更新:数组推导式已从标准中删除。引用MDN

The array comprehensions syntax is non-standard and removed starting with Firefox 58. For future-facing usages, consider using Array.prototype.map, Array.prototype.filter, arrow functions, and spread syntax.

数组推导语法是非标准的,从 Firefox 58 开始被移除。对于面向未来的用法,请考虑使用 Array.prototype.map、Array.prototype.filter、箭头函数和传播语法。

See this answerfor an example with Array.prototype.map:

有关示例,请参阅此答案Array.prototype.map

let emails = people.map(({ email }) => email);

let emails = people.map(({ email }) => email);

Original answer:

原答案:

Yes, JavaScript will support array comprehensionsin the upcoming EcmaScript version 7.

是的,JavaScript 将在即将推出的 EcmaScript 版本 7 中支持数组推导式。

Here's an example.

这是一个例子

var str =  "1234-5";
var ignore = "-";

console.log([for (i of str) if (!ignore.includes(i)) i]);

回答by ChadF

Not directly, but it's not hard to replicate.

不直接,但不难复制。

var string = "1234-5";

var forbidden = "-";

string.split("").filter(function(str){
    if(forbidden.indexOf(str) < 0) {
        return str;
    }
}).forEach(function(letter) { console.log(letter);});

I guess more directly:

我猜更直接:

for(var i=0 ; i < str.length ; i++) {
    if(forbidden.indexOf(str) < 0) {
        console.log(str[i]);
    }
}

But there's no built in way to filter in your for loop.

但是没有内置的方法来过滤你的 for 循环。

回答by Jaromanda X

Reading the code, I assume forbidden can have more than 1 character. I'm also assuming the output should be "12345"

阅读代码,我假设禁止可以有 1 个以上的字符。我还假设输出应该是“12345”

var string = "12=34-5";

var forbidden = "=-";

console.log(string.split("").filter(function(str){
    return forbidden.indexOf(str) < 0;
}).join(""))

If the output is "1" "2" "3" "4" "5" on separate lines

如果在单独的行上输出为“1”“2”“3”“4”“5”

var string = "12=34-5";

var forbidden = "=-";

string.split("").forEach(function(str){
    if (forbidden.indexOf(str) < 0) {
        console.log(str);
    }
});

回答by DRD

For "completeness"-sake, here's a shorter regexp version.

为了“完整性”,这里有一个较短的正则表达式版本。

var str =  "1234-5";
var ignore = "-=";

console.log(str.replace(new RegExp(ignore.split("").join("|")), "").split(""));

EDIT: To make sure that RegExp does not "choke" on special characters, ignorecan be implemented as regexp literal, instead of a string:

编辑:为了确保 RegExp 不会在特殊字符上“窒息”,ignore可以实现为 regexp 文字,而不是字符串:

var str =  "1234-5";
var ignore = /[\+=-]/;
console.log(str.replace(ignore, "").split(""));

回答by Henrik Vendelbo

It does have a poor mans version

确实有穷人版

const string = '1234-5'

const forbidden = '-'

print([int(i) for i in str(string) if i not in forbidden])
const result = string.split('').filter(char => char !== forbidden);
console.log(result)

In JS you can only iterate over single elements in array, so no extraction of multiple entries at a time like in Python.

在 JS 中,您只能迭代数组中的单个元素,因此无法像在 Python 中那样一次提取多个条目。

For this particular case you should use a RegExp to filter the string though.

对于这种特殊情况,您应该使用 RegExp 来过滤字符串。

回答by martin

You could easily achieve this behavior using an application functor.

您可以使用应用程序函子轻松实现此行为。

Array.prototype.ap = function(xs) {
  return this.reduce((acc, f) => acc.concat(xs.map(f)), []) 
}


const result = [x => x +1].ap([2])
console.log(result)

回答by Colin D Bennett

Given the question's Python code

鉴于问题的 Python 代码

print([int(i) for i in str(string) if i not in forbidden])

this is the most directtranslation to JavaScript (ES2015):

这是对 JavaScript (ES2015)最直接的翻译:

const string = '1234-5';
const forbidden = '-';

console.log([...string].filter(c => !forbidden.includes(c)).map(c => parseInt(c)));
// result: [ 1, 2, 3, 4, 5 ]

Here is a comparison of the Python and JavaScript code elements being used: (Python -> Javascript):

以下是所使用的 Python 和 JavaScript 代码元素的比较:(Python -> Javascript):

  • print -> console.log
  • iterate over characters in a string -> spread operator
  • list comprehension 'if' -> Array.filter
  • list comprehension 'for' -> Array.map
  • substr in str? -> string.includes
  • 打印 -> console.log
  • 迭代字符串中的字符 ->展开运算符
  • 列表理解 'if' -> Array.filter
  • 列表理解 'for' -> Array.map
  • str中的substr?-> string.includes

回答by VanBantam

JavaScript no longer supports array comprehensions.

JavaScript 不再支持数组推导式。

I too was looking for the JavaScript equivalent. Mozilla Developer's Network indicates that this functionality is no longer supported.The preferred syntax is referenced in the aforementioned link.

我也在寻找等效的 JavaScript。Mozilla 开发人员网络表明不再支持此功能。上述链接中引用了首选语法。