我有一個同義詞庫應用程序,因此用戶可以輸入「dog」作爲基本單詞,而「canine,hound,mutt」作爲同義詞。 然後將它們添加到數據庫中。 除了添加「狗」作爲基本詞,我想爲每個同義詞進行多個同時輸入,以便用戶不必返回並輸入「獵犬」,然後輸入「狗,犬,傻子」。這將涉及多個表單提交。創建數組鍵值和數組數組
基於上述例子中,我想標題到數據庫之前創建以下數據集:
var Keys =
[
dog,canine,mutt,hound
];
var Values = [
[mutt,canine,hound],[dog,mutt,hound],[canine,dog,hound],[dog,canine,mutt]
];
一旦我有這樣的,我可以通過每個按鍵做一個簡單的循環,並抓住內的相應陣列值,並執行我的插入。例如,當根據它們的長度進行迭代時,我會抓取索引2並獲取'mutt'鍵,然後獲取'[犬,狗,獵犬]'的值。到目前爲止,我嘗試執行所需的嵌套循環來實現這個數據集並沒有證明有效果。
到目前爲止,我已經嘗試過這一點,我希望的一些建議:
var baseWord = [];
baseWord.push("dog");
var synonyms = ["hound","mutt","canine"];
var words = baseWord.concat(synonyms);
console.log(words.length); //outputs 4
//new arrays to hold the result of the inner loop calculation
var Keys = [];
var Values = [];
for(var i = 0; i < words.length; i++){
//removing the inner loops makes this output, the 4 values from the 'words' variable. with the inclusion of the loops, we only get back 'dog'
keys.push(words[i]);
for(var x = 0; x < words.length; x++){
//I want to loop through the 'words' variable, and if current index of 'words' matches a value in tempValues(matches a different value of tempValues each time, which is what i'd want(it allows us to ignore the current key, and keep the values), then remove that particular value from tempValues, then push the remaining values in tempValues into our 'VAlues' array that we declared ouside all of these loops
var tempValues = words;
//console.log("tempvalues is :: %s", JSON.stringify(tempValues));
for(var o = 0; o < words.length; o++){
if(words[o] === words[x]){
//get rid of the value in tempValues that is equals to the value of the key in the outer loop(for this particular iteration)
tempValues.splice(tempValues[o]);
}
console.log(JSON.stringify(tempValues));
}
Values.push(tempValues);
};
};
console.log("the new keys array is :: %s", JSON.stringify(Keys)); //keep getting dog
console.log("the new values array is :: %s", JSON.stringify(Values)); //keep getting [[]]
是您的PHP代碼重要? – Scuzzy
不,但這是除了陣列以外唯一的其他建議,我認爲這將有助於暴露我認爲是一個常見問題。 – OisinFoley