Esta es una pregunta importante, ¿cómo convierto el código C a Javascript? Por favor, ayúdame con esto para mi proyecto.
#include <stdio.h> int MAXSIZE = 8; int stack[8]; int top = -1; int isempty() { if (top == -1) return 1; else return 0; } int isfull() { if (top == MAXSIZE) return 1; else return 0; } int peek() { return stack[top]; } int pop() { int data; if (!isempty()) { data = stack[top]; top = top - 1; return data; } else { printf("Could not retrieve data, Stack is empty.\n"); } } int push(int data) { if (!isfull()) { top = top + 1; stack[top] = data; } else { printf("Could not insert data, Stack is full.\n"); } } int main() { // push items on to the stack push(3); push(5); push(9); push(1); push(12); push(15); printf("Element at top of the stack: %d\n", peek()); printf("Elements: \n"); while (!isempty()) { int data = pop(); printf("%d\n", data); } printf("Stack full: %s\n", isfull() ? "true" : "false"); printf("Stack empty: %s\n", isempty() ? "true" : "false"); return 0; }La salida es:
Element at top of the stack: 15 Elements: 15 12 1 9 5 3 Stack full: false Stack empty: trueUn poco de ayuda.
C | JS -----------------|------------------ int x; | var x; -----------------|------------------ int xs[n]; | var xs = []; -----------------|------------------ printf(...) | console.log(...) -----------------|------------------ int f (int x) { | function f (x) { ... | ... return y; | return y; } | }La sintaxis restante de su publicación es casi idéntica en C y JS.
Presione F12 en su navegador (Chrome o Firefox) y diviértase con JavaScript en la pestaña "Consola", es un buen punto de partida :-) Por ejemplo, copie y pegue el siguiente código en la consola del navegador y presione ENTER .
function add (a, b) { return a + b; } console.log("1 + 1 =", add(1, 1)); add(1, 2);