[英]JS push array into array not working
這是我的代碼無法正常工作,我不希望它將相同的數組推入該數組
var fruits = [];
var news={from,theword};
if (fruits.indexOf(news) <0){ // or .includes(news)
fruits.push(news);}.
OUTPUT
[ { from: 'rubuno@.me',
theword: 'birakma beni derken birakilirmi bu kadin 😉😚' },
{ from: 'rubuno@.me',
theword: 'birakma beni derken birakilirmi bu kadin 😉😚' } ]
這是因為{from,theword}
上線2和{from,theword}
第6行看起來是一樣的,但它們實際上是不同的對象。
例如, {} === {}
返回false
。 當它們看起來相同時,只有基元(字符串,數字,布爾值,...)相等: 'a' === 'a'
返回true
。
因此,如果在第6 {from,theword}
更改為news
,它將指向同一對象,並且您的代碼將起作用(數組中只有1個對象)。
另外, {from,theword}
符號在javascript中是相當新的。 您確定要這個嗎? 就像說{from: from, theword: theword}
。
嘗試使用Array#find
方法。別忘了添加!
首先是if
條件
更新
var fruits = [{from: 'rubuno@ .me', theword: 'gelmis gecmis en guzel kadin sesi yuregine saglik funda'}, { from: 'rubuno@ .me', theword: 'gelmis gecmis en guzel kadin sesi yuregine saglik funda'}] var news = { from: 'rubuno@ .me', theword: 'gelmis gecmis en guzel kadin sesi yuregine saglik funda'} if (!fruits.find(a => a.from == news.from && a.theword == news.theword)) { //check is present r not fruits.push(news); //then push is not inside the array } console.log(fruits) //is passing one time only
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.