gpt4 book ai didi

javascript - 如何测试变量中的某个数字?

转载 作者:行者123 更新时间:2023-11-28 19:13:44 25 4
gpt4 key购买 nike

假设我有一个名为 testtest = 123456789; 的变量。然后我有另一个名为 anotherTestanotherTest = 1234; 的变量。我该如何编写一个程序来测试变量是否包含数字 5?那么,如何将变量分为两组,一组变量中有数字“5”,另一组变量中没有数字“5”呢?有没有简单的方法可以做到这一点?

最佳答案

How would I make a program that can test whether a variable has the digit 5 or not?

您可以使用字符串和 indexOf 轻松做到这一点:

if (String(test).indexOf("5") !== -1) {
// It has a 5 in it
}

Then, how could it sort the variables into two groups of which one group of variables has the digit "5" within it and the other without?

您无法将变量分组,但您当然可以将分组。例如,这会循环遍历一个数组,并将值添加到 with5without5 数组,具体取决于该值是否包含数字 5:

var a = [
1234,
12345,
123123,
555555
];
var with5 = [];
var without5 = [];
a.forEach(function(value) {
if (String(value).indexOf("5") === -1) {
without5.push(value);
} else {
with5.push(value);
}
});
snippet.log("with5: " + with5.join(", "));
snippet.log("without5: " + without5.join(", "));
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

<小时/>

上面假设以 10 为基数(十进制)的字符串,但您可以使用 Number#toString(base) 轻松地对十六进制或八进制或您喜欢的任何其他基数执行相同的操作。例如:

var s = num.toString(16);

...会将 num 的值分配给 s 作为十六进制(基数为 16)字符串。

关于javascript - 如何测试变量中的某个数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30293498/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com