我有初学者的脚本编写技能,正在使用一种JavaScript的形式,ECMA-262,这是在一个名为Opus Pro (英国数字工作室)的程序中找到的。
我一直在网上搜索,但没有成功,想要找到一种方法来合并和替换两个数组中的元素到第三个合并的数组中。我在这个网站上找到了一些脚本,但是它们使用了像"push“这样的函数,这些函数在这个脚本语言中是找不到的,所以不能使用。
我当前的脚本为一组随机选择的数字(math.random)1-6创建一个数组,需要修改以创建两个数组(1-3和4-6),然后交替合并第一个数组中的值和第二个数组中的值,直到新数组中有6个来自这些(子)数组的值:
当前未修改的脚本:
function separate()
{
for(i=1;i<=listamount;i++)
{
//create 6 random numbers from 1-6
temp = Math.round(Math.random()*(6))
if (temp == 0){temp = 1}
if (temp == 7){temp = 6}
randomset[i] = temp
}
}这需要修改,以便最终的随机列表数组(称为newrandomlisti)将是一个交替的混合,如2,6,1,4,3,5,但由2个随机排序/创建的子数组(1-3和4-6)合并而成。来自每个随机排序/构造的子数组的交替值对于项目中其余脚本的功能至关重要。我尝试了许多想法,但都没有成功。
感谢您的帮助。
发布于 2012-07-26 04:40:29
ECMA-262具有数组对象,该对象具有.push()方法。您可以自己在15.4.4.7节的ECMA spec中看到它。
要通过交替使用每个数组中的随机元素来合并两个数组,可以执行以下操作:
function mergeTwoRandom(arr1, arr2) {
function extractRandom(arr) {
var index = Math.floor(Math.random() * arr.length);
var result = arr[index];
// remove item from the array
arr.splice(index, 1);
return(result);
}
var result = [];
while (arr1.length || arr2.length) {
if (arr1.length) {
result.push(extractRandom(arr1));
}
if (arr2.length){
result.push(extractRandom(arr2));
}
}
return(result);
}如果你想在没有.push()的情况下完成,你可以这样做:
function mergeTwoRandom(arr1, arr2) {
function extractRandom(arr) {
var index = Math.floor(Math.random() * arr.length);
var result = arr[index];
// remove item from the array
arr.splice(index, 1);
return(result);
}
var result = [];
while (arr1.length || arr2.length) {
if (arr1.length) {
result[result.length] = extractRandom(arr1);
}
if (arr2.length){
result[result.length] = extractRandom(arr2);
}
}
return(result);
}如果你也没有.splice(),你可以这样做:
function mergeTwoRandom(arr1, arr2) {
function removeItem(arr, index) {
for (var i = index; i < arr.length - 1; i++) {
arr[i] = arr[i + 1];
}
arr.length = arr.length - 1;
}
function extractRandom(arr) {
var index = Math.floor(Math.random() * arr.length);
var result = arr[index];
// remove item from the array
removeItem(arr, index);
return(result);
}
var result = [];
while (arr1.length || arr2.length) {
if (arr1.length) {
result[result.length] = extractRandom(arr1);
}
if (arr2.length){
result[result.length] = extractRandom(arr2);
}
}
return(result);
}https://stackoverflow.com/questions/11658089
复制相似问题