gpt4 book ai didi

jquery - 使用 jQuery 映射函数后如何将数组转换为字符串?

转载 作者:行者123 更新时间:2023-12-03 22:56:33 25 4
gpt4 key购买 nike

我正在使用.map函数将元素转换为数组,然后我想将此数组转换为字符串:

javascript:

var selectedElements = $('.data').map(function() {
return $(this).hasClass('selected') ? 'true' : 'false';
});

var A = ['Sunday','Monday','Tuesday','Wednesday','Thursday']
A = A + "";

var string = selectedElements + "";

console.log("\ndebug:");
console.log(selectedElements);
console.log(A);
console.log(string );​

html:

<div class='data'></div>
<div class='data selected'></div>
<div class='data selected'></div>
<div class='data'></div>
<div class='data'></div>
<div class='data'></div>
<div class='data'></div>

控制台输出:

debug: fiddle.jshell.net:29
["false", "true", "true", "false", "false", "false", "false"]
Sunday,Monday,Tuesday,Wednesday,Thursday
[object Object]

在这里摆弄:http://jsfiddle.net/F8ufE/

如何将 selectedElements 转换为数组?

最佳答案

根据.map() docs :

As the return value is a jQuery object, which contains an array, it's very common to call .get() on the result to work with a basic array.

因此,如果您想获取实际的数组,可以使用 get 方法,如下所示:

var selectedElements = $('.data').map(function() {
return $(this).hasClass('selected') + "";
}).get();

要将数组转换为字符串,您可以使用 join 方法:

selectedElements = selectedElements.join()

关于jquery - 使用 jQuery 映射函数后如何将数组转换为字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12690468/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com