js list merge
结果用:
var authorsIllustrators = [] var bookAuthors = curBookDict["author"]["bookAuthors"] console.log("bookAuthors=", bookAuthors) if (bookAuthors) { authorsIllustrators.concat(bookAuthors) } console.log("authorsIllustrators=", authorsIllustrators) var illustrators = curBookDict["author"]["illustrators"] console.log("illustrators=", illustrators) if (illustrators) { authorsIllustrators.concat(illustrators) } console.log("authorsIllustrators=", authorsIllustrators) var authorsIllustratorsStr = listToStr(authorsIllustrators) console.log("authorsIllustratorsStr=", authorsIllustratorsStr)
输出:
book_detail.js:130 bookAuthors= ["Audrey Wood"] 11:22:30.957 book_detail.js:134 authorsIllustrators= [] 11:22:30.958 book_detail.js:136 illustrators= [] 11:22:30.959 book_detail.js:140 authorsIllustrators= [] 11:22:30.960 book_common.js:24 listToStr: listValue=[] 11:22:30.961 book_detail.js:142 authorsIllustratorsStr=
竟然第一次空数组contact一个有值的数组,结果是空
-》看来是不支持空数组
改为:
var authorsIllustrators = [] var bookAuthors = curBookDict["author"]["bookAuthors"] console.log("bookAuthors=", bookAuthors) if (bookAuthors) { authorsIllustrators = bookAuthors } console.log("authorsIllustrators=", authorsIllustrators) var illustrators = curBookDict["author"]["illustrators"] console.log("illustrators=", illustrators) if (illustrators) { if (authorsIllustrators) { authorsIllustrators = illustrators } else { authorsIllustrators.concat(illustrators) } } console.log("authorsIllustrators=", authorsIllustrators) var authorsIllustratorsStr = listToStr(authorsIllustrators) console.log("authorsIllustratorsStr=", authorsIllustratorsStr)
竟然也不对:
bookAuthors= ["Audrey Wood"] 11:25:25.080 book_detail.js:134 authorsIllustrators= ["Audrey Wood"] 11:25:25.081 book_detail.js:136 illustrators= [] 11:25:25.082 book_detail.js:144 authorsIllustrators= []
js merge empty list
后来改为:
authorsIllustrators = authorsIllustrators.concat(bookAuthors) authorsIllustrators = authorsIllustrators.concat(illustrators)
即可:
bookAuthors= ["Audrey Wood"] 11:29:51.980 book_detail.js:132 illustrators= [] 11:29:51.982 book_detail.js:150 authorsIllustrators= ["Audrey Wood"]
【总结】
此处用:
var authorsIllustrators = [] authorsIllustrators = authorsIllustrators.concat(bookAuthors) authorsIllustrators = authorsIllustrators.concat(illustrators)
即可实现数组合并,且也支持其中任意一个数组为空
而前面之所以:
if (bookAuthors) { authorsIllustrators.concat(bookAuthors) }
出错,是因为:
忘了把合并后的数组返回给原先的变量。。。。
转载请注明:在路上 » 【已解决】js中如何合并两个数组且支持空数组合并