我正在使用getJSON
作为我的JSON数据项,如下所示:
$.getJSON(projects, function (json) {
var firstThree = json.sort(function(a, b) { return a.Variable1 < b.Variable1 ? 1 : -1; })
.slice(0, 3);
var related = firstThree;
var i = '';
$.each(json, function(i) {
var sizeClass = JSON.stringify(related[i].pname);
console.log('sifzdfze'+sizeClass);
});
我检查了控制台,获取了sizeClass项,它有效。但是它也显示错误:
related[i] is undefined
有什么问题?谢谢!
答案 0 :(得分:0)
根据您的代码,您将textTest1();
textTest2();
function textTest1(){
var pText1 = $('p.textTest1').text();
console.log(pText1.match(/[^\s]+/g).join(' ').length);
console.log(pText1.match(/[^\s]+/g).join(' '));
}
function textTest2(){
var pText2 = $('p.textTest2').text();
console.log(pText2.match(/[^\s]+/g).join(' ').length);
console.log(pText2.match(/[^\s]+/g).join(' '));
}
作为数组访问。所以你应该迭代数组中的项目。在您的情况下,<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="textTest1">text test</p>
<p class="textTest2">
text
test
</p>
为related
,因为您正在尝试访问超出特定数组范围的项目。
related[i]
应该是
undefined
同样在上面的行中,创建一个范围为$.each(json, function(i) {
回调的$.each(related, function(val, i) {
。所以不需要在上面的行中声明它。
这里i
是迭代中的当前值,其索引为each
。它可以简化为
val