【发布时间】:2012-12-17 10:23:50
【问题描述】:
Javascript(使用 jQuery):
var paragraphs = [
['This is my first paragraph content of the first array', 'This is my second paragraph content of the first array', 'This is my third paragraph content of the first array'],
['This is my first paragraph content of the second array', 'This is my second paragraph content of the second array', 'This is my third paragraph content of the second array']
],
text_box_value,
unused_paragraphs = null;
$(document).ready(function(){
$('input#text_box').keyup(function(){
text_box_value = $(this).val();
});
$('input#submit_button').click(function(){
if(unused_paragraphs === null) {
unused_paragraphs = paragraphs;
}
for(var i = 0; i < unused_paragraphs.length; i++) {
if(unused_paragraphs[i].length == 0)
unused_paragraphs[i] = paragraphs[i];
while(unused_paragraphs[i].length != 0) {
var rand = Math.floor(Math.random() * unused_paragraphs[i].length);
if(unused_paragraphs[i][rand].search(text_box_value) !== -1) {
$("#paragraphs_container").append('<p>' + unused_paragraphs[i][rand] + '</p>');
break;
}
unused_paragraphs[i].splice(rand, 1);
}
}
console.log(unused_paragraphs);
console.log(paragraphs);
});
});
我的问题是为什么当我在 unused_paragraphs 变量上使用 splice 方法时,它也会从 paragraphs 变量中删除值
稍后编辑 JSFiddle
【问题讨论】:
-
听起来你只有一个数组,但有两个变量引用它。
标签: javascript splice