gpt4 book ai didi

javascript - 修改后保留原始数组顺序?

转载 作者:行者123 更新时间:2023-12-03 01:25:32 25 4
gpt4 key购买 nike

我正在尝试修复数据库中行的命名约定格式错误的 View 。我无法在查询本身中更正这些约定,因为它会影响网站内的许多功能。因此,我决定使用 JavaScript 正确地重命名它们,以便它们在 View 中以正确的命名约定显示。

为此,我必须编写查询,使其返回一个虚构的数组,如下所示:

原始数组

['Tree_Domestic'、兔子、独 Angular 兽、Cheetah_Domestic、鲨鱼、Whale_Domestic]

我想要的是扫描整个数组,只找到具有“_domestic”或“_international”的条目,并将其替换为“_international”。例如,[Rabbit,Unicorn,Shark] 没有 _domestic,也没有 _international,所以我希望它们像这样:

[Rabbit_International,Unicorn_International ,Shark_International]

我成功地做到了这一点,但我遇到了最后一个问题,

它按字母顺序修改了数组的顺序,但我不希望这样。我希望数组看起来像这样:

['Tree_Domestic'、Rabbit_International、Unicorn_International、Cheetah_Domestic、Shark_International、Whale_Domestic]

我需要它看起来像这样的原因是因为在我的查询中,我也在计算最受欢迎的行,如果我用我的计数修改数组,计数将不会与数组保持正确的顺序使用修改后的数组排序的项目。

这是我的查询:

$sql = 'SELECT animals,
COUNT(*)
FROM fictional_signup
WHERE usergroup NOT IN (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
GROUP BY popular
ORDER BY COUNT(*) DESC';

Javascript

var renameLocations = [];

dataLabel = <?php echo json_encode($locations) ?>;
dataCount = <?php echo json_encode($count) ?>;

for(t = 0; t < dataLabel.length; t++){
if(dataLabel[t].includes('_Domestic') || dataLabel[t].includes('_International')){
renameLocations.push(dataLabel[t]);
}
}
for(z = 0; z < dataLabel.length; z++){
if(!dataLabel[z].includes('_Domestic') && !dataLabel[z].includes('_International')){
renameLocations.push(dataLabel[z] + "_International");
}
}

// Returns the correct naming conventions but the order is incorrect with the count.
console.log(renameLocations);

最佳答案

您可以使用Array.prototype.map()函数创建一个带有修改后的条目的新数组。

/*
$locations = [
'Tree_Domestic',
'Rabbit',
'Unicorn',
'Cheetah_Domestic',
'Shark',
'Whale_Domestic'
]
*/
dataLabel = <?php echo json_encode($locations) ?>.map(
// "e" represents each entry in the array, one at a time
function(e){
// if the entry ends with _Domestic or _International,
// then just keep the value
if (e.endsWith('_Domestic') || e.endsWith('_International'))
return e;
// otherwise, append "_International" to the entry and use that
else
return e + "_International";
}
)

产品:

[
"Tree_Domestic",
"Rabbit_International",
"Unicorn_International",
"Cheetah_Domestic",
"Shark_International",
"Whale_Domestic"
]

关于javascript - 修改后保留原始数组顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51565860/

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