gpt4 book ai didi

用于循环查找之前,等于,之间和之后值的Javascript?

转载 作者:行者123 更新时间:2023-11-29 20:56:45 29 4
gpt4 key购买 nike

我觉得我遗漏了一些明显的东西。这是一个简单的例子来说明我的问题。

我希望 current = 3 返回“之前”。 current = 4 应该返回“key-two”,current = 5 应该返回“between”,current = 7 应该返回“key-two”,current = 8 应该返回“after”。

此代码未按预期工作。将电流设置为 7 返回“key-two”,将其设置为 8 或更大返回“after”将其设置为任何其他数字返回之间。

let items = []
items['key-one'] = 4
items['key-two'] = 7

let current = 3

let results = ''

for(let key in items) {
let keyOne = ''
let keyTwo = ''
if (key === 'key-one') {
keyOne = items[key]
}
if (key === 'key-two') {
keyTwo = items[key]
}
if (current < keyOne) {
results = 'before'
}
else if (current === items[key]) {
results = key
}
else if (current > keyOne && current < keyTwo) {
results = 'between'
}
else if (current > keyTwo) {
results = 'after'
}
}
document.write(results)

最佳答案

每次循环迭代时,您都有效地创建了一个新变量。将 keyOnekeyTwo 放在循环之外。

let items = []
items['key-one'] = 4
items['key-two'] = 7

let current = 3

let results = ''
let keyOne = ''
let keyTwo = ''

for(let key in items) {

if (key === 'key-one') {
keyOne = items[key]
}
if (key === 'key-two') {
keyTwo = items[key]
}
if (current < keyOne) {
results = 'before'
}
else if (current === items[key]) {
results = key
}
else if (current > keyOne && current < keyTwo) {
results = 'between'
}
else if (current > keyTwo) {
results = 'after'
}
}
document.write(results)

这足以让您现有的代码正常工作,但还有很多可以改进的地方。考虑这个方法..

function positionInRange(point, low, high){
return point > high ? "after" :
point < low ? "before" :
point > low && point < high ? "between" :
point == low ? "key-1" : "key-2"
}

var items = {
"key-1": 4,
"key-2": 7
}

var results = positionInRange(3, items['key-1'], items['key-2']);
document.write(results)

关于用于循环查找之前,等于,之间和之后值的Javascript?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48955880/

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