このアプローチは、埋め込まれた配列を確認するために再帰を使用します。
var a = ['[1,2,3,4]','{"a":"4","b":true,"c":[5,6,7]}','{"a":[1,"2",3],"b":2,"c":["1","2","3"]}','{xds}'];
var i,j,l = a.length;
function testForArray(v,depth) {
var e,f;
// Ensure this is not deeper than the first level
if (depth > 1) {
return false;
}
// Check if v is an array
if (Array.isArray(v)) {
// Use filter to find any elements which are not numeric
// In this case, "2" is considered a string, not a number
f = v.filter(function(e) {
return (isNaN(e) || typeof e === "string");
});
// If the filtered array is empty, all elements were numeric
if (f.length === 0) {
return true;
}
// The filtered array was not empty
return false;
} else {
// If v is an object
if (typeof v === "object") {
// Loop through all the properties
for (e in v) {
// Check if each property is an array, incrementing the depth
if (testForArray(v[e],depth+1) === false) {
// If the array is non-numeric, fail
return false;
}
}
// Return true if it has not yet failed
return true;
}
}
// Return null if the element tested was not an array or object
return null;
}
// Test the function
for (i = 0; i < l; i++) {
console.log(a[i]);
try {
j = JSON.parse(a[i]);
console.log(testForArray(j,0));
} catch (e) {
console.log('caught: '+e);
}
}
最初に行ったことはありますか?問題に関する多くの情報を知らなければ、https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/isNaN –
をご覧ください。この問題の標準的な解決策はありません。いくつかのコードを書く必要があります。 – user2182349
したがって、数値だけを含むオブジェクト内のすべての配列を検索したいですか? –