[英]How can I write a function which gives the output in the below format?
编写一个 function,给定以下输入,生成给定的 output
输入:["John", false, "Doe", 46, 6.5, 7, true];
Output:[[“John”,“Doe”],[46, 7],[6.5],[假,真]];
function reFactor() { var input = ["John", false, "Doe", 46, 6.5, 7, true]; for (var i=0; i <input.length; i++) { if (typeof input[i] === "string") { alert("String"); } else if (typeof input[i] === "number") { alert("Number"); } else if (typeof input[i] === "boolean") { alert("Boolean"); } } }
<input type="button" onclick="reFactor()" value="Click">
我能够达到这一步。 如何在这里使用 map function?
我能想到的最简单的方法是为您需要的每种类型分别设置 arrays:
function reFactor() { var input = ["John", false, "Doe", 46, 6.5, 7, true]; var stringInput = []; var numberInput = []; var booleanInput = []; for (var i=0; i <input.length; i++) { if (typeof input[i] === "string") { stringInput.push(input[i]) } else if (typeof input[i] === "number") { numberInput.push(input[i]) } else if (typeof input[i] === "boolean") { booleanInput.push(input[i]) } } var result = [stringInput, numberInput, booleanInput] console.log(result) }
<input type="button" onclick="reFactor()" value="Click">
要区分“浮点数”和“整数”数,您需要使用一些技巧。 请参阅: 如何区分 JavaScript 中的一位十进制浮点数和 integer
我认为布鲁诺的答案就是你所要求的。 但只是为了好玩,一种更通用的按类型分解值的方法:
Javascript:
function reFactor(input) {
const result = {}
input.map((val) => {
const key = typeof val;
if (key in result) {
result[key].push(val);
} else {
result[key] = [val]
}
}, {})
return result;
}
const x = ["John", false, "Doe", 46, 6.5, 7, true];
const rX = reFactor(x);
console.log(rX)
Typescript:
const VarType = ["string" , "number" , "bigint" , "boolean" , "symbol" , "undefined" , "object" , "function"] as const
type ResultSetValue = {
[key: string]: any[]
}
function reFactor(input: any[]) {
const result: ResultSetValue = {}
input.map((val) => {
const key = typeof val;
if (key in result) {
result[key].push(val);
} else {
result[key] = [val]
}
}, {} as ResultSetValue)
return result;
}
const x = ["John", false, "Doe", 46, 6.5, 7, true];
const rX = reFactor(x);
console.log(rX)
这将返回:
{
string: [ 'John', 'Doe' ],
boolean: [ false, true ],
number: [ 46, 6.5, 7 ]
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.