JavaScript数组计数和删除零

发布于 2025-01-19 13:38:39 字数 342 浏览 1 评论 0原文

我有一个数组 let test = [0,0,0,0,0,0,0,0,0,0,3,4,5,6,3,0, 0,0,0,4,6,7]

我需要从起点计算零的数量,在本例中为“9”,直到值 3

下一步想要只删除前九个条目。数组其余部分中的剩余零必须保留。

预期结果

计数 = 9 让测试= [3,4,5,6,3,0,0,0,0,4,6,7]

I have an Array let test = [0,0,0,0,0,0,0,0,0,0,3,4,5,6,3,0,0,0,0,4,6,7]

I need to count the amount of zero's from the starting point in this case "9" upto value 3

Next want to only delete the first nine entries . The remaining zero's in the rest of the array must remain.

Expected Result

Count = 9
Let Test = [3,4,5,6,3,0,0,0,0,4,6,7]

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

完美的未来在梦里 2025-01-26 13:38:39

首先,示例的结果应该是 Count = 10,因为 0 有 10 个。

我想您想定义一个函数来获取结果。那可以是:

const func = (arr) => {
    let count = 0
    for (let i in arr) {
        if (arr[i] != 0) {
            break
        }
        count++
    }
    return [count, arr.slice(count)]
}

// Test:
const array = [0,0,0,0,0,0,0,0,0,0,3,4,5,6,3,0,0,0,0,4,6,7]
console.log(`Count = ${func(array)[0]}, Array = ${func(array)[1]}`)
// Result should be Count = 10, Array = [3,4,5,6,3,0,0,0,0,4,6,7]

First of all, the result of your example should be Count = 10 because there are 10 of 0.

I suppose you want to define a function to get the result. That can be:

const func = (arr) => {
    let count = 0
    for (let i in arr) {
        if (arr[i] != 0) {
            break
        }
        count++
    }
    return [count, arr.slice(count)]
}

// Test:
const array = [0,0,0,0,0,0,0,0,0,0,3,4,5,6,3,0,0,0,0,4,6,7]
console.log(`Count = ${func(array)[0]}, Array = ${func(array)[1]}`)
// Result should be Count = 10, Array = [3,4,5,6,3,0,0,0,0,4,6,7]
只为守护你 2025-01-26 13:38:39

请尝试以下代码:

function firstZeros(r) {

    var c = 0,s=true,nr=[];
    for(let ri of r){
        if(s && ri==0){
            c++;
        }else{
            s=false;        
            nr.push(ri);
        }
    }
    
    return {'count':c,'data':nr};
}


let test = [0,0,0,0,0,0,0,0,0,3,4,5,6,3,0,0,0,0,4,6,7];

let res = firstZeros(test);

console.log('Count='+res.count);
console.log('Test='+res.data);

谢谢

Please try the following code :

function firstZeros(r) {

    var c = 0,s=true,nr=[];
    for(let ri of r){
        if(s && ri==0){
            c++;
        }else{
            s=false;        
            nr.push(ri);
        }
    }
    
    return {'count':c,'data':nr};
}


let test = [0,0,0,0,0,0,0,0,0,3,4,5,6,3,0,0,0,0,4,6,7];

let res = firstZeros(test);

console.log('Count='+res.count);
console.log('Test='+res.data);

Thanks

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文