javascript 将空值映射到数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16479744/
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
Map null values to array
提问by Johan
Why isn't null
added to my keys
array below?
为什么没有null
添加到我keys
下面的数组中?
HTML
HTML
<input type="radio" data-codekey="1"/>
<input type="radio" data-codekey="null"/>
JS
JS
$(function(){
var keys = $step.find('input[type="radio"]').map(function (i, el) {
return $(el).data('codekey');
}).get();
console.log(keys); // [1]
//desired result: [1, null]
});
回答by nnnnnn
From the .map()
documentation:
If the function returns null or undefined, no element will be inserted.
如果函数返回 null 或 undefined,则不会插入任何元素。
The .data()
function does type conversion and (apparently) assumes the string "null"
should be converted to the value null
. It also converts the string"1"
to the number 1
.
该.data()
函数进行类型转换,并且(显然)假定"null"
应该将字符串转换为 value null
。它还将字符串"1"
转换为数字1
。
Use .attr()
instead of .data()
and you'll get the actual string "null"
:
使用.attr()
而不是.data()
你会得到实际的字符串"null"
:
return $(el).attr('data-codekey');
If you want an actual null
you can't use .map()
, you'd have to rewrite it with an .each()
loop or something:
如果你想要一个null
你不能使用的实际.map()
,你必须用.each()
循环或其他东西重写它:
var keys = [];
$step.find('input[type="radio"]').each(function () {
keys.push( $(this).data('codekey') );
});
回答by Lee
Over a year later, it appears that either things have changed with map() or the original answer missed something in the docs.
一年多后,似乎 map() 发生了变化,或者原始答案遗漏了docs 中的某些内容。
The function can return:
- the translated value, which will be mapped to the resulting array
- null or undefined, to remove the item
- an array of values, which will be flattened into the full array
该函数可以返回:
- 转换后的值,将映射到结果数组
- 空或未定义,删除项目
- 一组值,将被展平为完整的数组
The solution here is in the last bullet: simply return an array containing a single element, even if it's null. The arrays will be flattened into the results, and the nulls will not be removed:
这里的解决方案在最后一个项目符号中:简单地返回一个包含单个元素的数组,即使它为空。数组将被展平到结果中,并且不会删除空值:
$([ null, null, null, 1, null]).map(function (i, el) {
return [ el ];
}).get();
Gets this result:
得到这个结果:
[ null, null, null, 1, null ]
回答by gdoron is supporting Monica
If the function returns null or undefined, no element will be inserted.
如果函数返回 null 或 undefined,则不会插入任何元素。
You can cast to string like:
您可以转换为字符串,如:
$(el).data('codekey') + "";
Read this: Casting to string in JavaScript
阅读本文:在 JavaScript 中转换为字符串
回答by Joel Christophel
You can simply move the .get()
call before .map()
. This will have you using the more predictable Array.map()function, which allows null
:
您可以简单地将.get()
呼叫移到之前.map()
。这将使您使用更可预测的Array.map()函数,它允许null
:
var keys = $step.find('input[type="radio"]').get().map(function (el) {
return $(el).data('codekey');
});